如何制作检查包来改变调用者本地人

时间:2017-01-08 15:00:45

标签: python variables scope inspect locals

我正在尝试编写一个save/load命令,就像MATLAB中的命令一样(能够将局部变量保存到磁盘或将它们加载到当前上下文中,或者用MATLAB的术语加载工作空间)。

我编写了以下代码,但它似乎不起作用,因为外部作用域中的变量没有被替换,因为内存复制发生在某处。

以下是代码:

import shelve
import logging
import inspect

logger = logging.getLogger()
def save_locals(filename, keys=None):
    my_shelf = shelve.open(filename, 'n')  # 'n' for new
    caller_locals = inspect.stack()[1][0].f_locals
    if keys is None:
        keys = caller_locals.keys()
    for key in keys:
        try:
            my_shelf[key] = caller_locals[key]
        except TypeError:
            #
            # __builtins__, my_shelf, and imported modules can not be shelved.
            #
            print('ERROR shelving: {0}'.format(key))
    my_shelf.close()


def load_locals(filename, keys=None):
    my_shelf = shelve.open(filename)
    caller_locals = inspect.stack()[1][0].f_locals
    if keys is None:
        keys = list(my_shelf.keys())
    for key in keys:
        try:
            caller_locals[key] = my_shelf[key]
        except ValueError:
            print('cannot get variable %s'.format(key))

以下测试失败:

from unittest import TestCase
from .io import save_locals, load_locals

class TestIo(TestCase):
    def test_save_load(self):
        sanity = 'sanity'
        an_int = 3
        a_float = 3.14
        a_list = [1, 2, 3]
        a_dict = [{'a': 5, 'b': 3}]
        save_locals('temp')
        an_int = None
        a_float = None
        a_list = None
        a_dict = None
        load_locals('temp')
        self.assertIn('an_int', locals())
        self.assertIn('a_float', locals())
        self.assertIn('a_list', locals())
        self.assertIn('a_dict', locals())
        self.assertEqual(an_int, 3)
        self.assertEqual(a_float, 3.14)
        self.assertEqual(a_list, [1, 2, 3])
        self.assertEqual(a_dict, [{'a': 5, 'b': 3}])

当我在load_locals内部断点时,我可以看到它改变了f_locals字典,但是当函数返回时它们不会改变。

1 个答案:

答案 0 :(得分:1)

不,您无法动态更新本地变量。原因是因为本地符号表被保存为C数组以进行优化,locals()frame.f_locals最终都将副本返回到该本地符号表。官方的回应是修改locals()具有未定义的行为。 This线程谈了一下。

它最终会变得奇怪,因为每次调用locals()frame.f_locals都会返回相同的字典,这会在不同的时间重新同步。这里只需调用frame.f_locals即可重置本地

def test_locals():
    frame = inspect.stack()[1][0]
    caller_locals = frame.f_locals
    caller_locals['an_int'] = 5
    print(caller_locals)
    _ = frame.f_locals
    print(caller_locals)


def call_test_locals():
    an_int = 3
    test_locals()


call_test_locals()

输出:

{'an_int': 5}
{'an_int': 3}

行为将取决于Python实现以及可能的其他边缘情况,但是一些示例(1)变量已定义且未更新; (2)变量未定义并更新; (3)变量已定义并随后被删除且未更新。

def test_locals():
    frame = inspect.stack()[1][0]
    caller_locals = frame.f_locals
    caller_locals['an_int'] = 5


def call_test_locals1():
    an_int = 3
    print('calling', locals())
    test_locals()
    print('done', locals())


def call_test_locals2():
    print('calling', locals())
    test_locals()
    print('done', locals())


def call_test_locals3():
    an_int = 3
    del an_int
    print('calling', locals())
    test_locals()
    print('done', locals())


print('\n1:')
call_test_locals1()
print('\n2:')
call_test_locals2()
print('\n3:')
call_test_locals3()

输出:

1:
calling {'an_int': 3}
done {'an_int': 3}

2:
calling {}
done {'an_int': 5}

3:
calling {}
done {}

如果您正在运行Python 2,您可以使用exec在本地命名空间中执行字符串,但它不能在Python 3中工作,并且通常可能是个坏主意。

import shelve
import logging
import inspect

logger = logging.getLogger()
def save_locals(filename, keys=None):
    my_shelf = shelve.open(filename, 'n')  # 'n' for new
    caller_locals = inspect.stack()[1][0].f_locals
    if keys is None:
        keys = caller_locals.keys()
    for key in keys:
        try:
            my_shelf[key] = caller_locals[key]
        except TypeError:
            #
            # __builtins__, my_shelf, and imported modules can not be shelved.
            #
            print('ERROR shelving: {0}'.format(key))
    my_shelf.close()



def load_locals_string(filename, keys=None):
    my_shelf = shelve.open(filename)
    if keys is None:
        keys = list(my_shelf.keys())
    return ';'.join('{}={!r}'.format(key, my_shelf[key]) for key in keys)

from unittest import TestCase
from .io import save_locals, load_locals

class TestIo(TestCase):
    def test_save_load(self):
        sanity = 'sanity'
        an_int = 3
        a_float = 3.14
        a_list = [1, 2, 3]
        a_dict = [{'a': 5, 'b': 3}]
        save_locals('temp')
        an_int = None
        a_float = None
        a_list = None
        a_dict = None
        exec load_locals_string('temp')
        self.assertIn('an_int', locals())
        self.assertIn('a_float', locals())
        self.assertIn('a_list', locals())
        self.assertIn('a_dict', locals())
        self.assertEqual(an_int, 3)
        self.assertEqual(a_float, 3.14)
        self.assertEqual(a_list, [1, 2, 3])
        self.assertEqual(a_dict, [{'a': 5, 'b': 3}])

在Python 2中,exec使用PyFrame_LocalsToFast将变量复制回本地范围,但不能在Python 3中复制,因为exec是一个函数。 Martijn Pieters有一个很好的帖子。