Python:如何动态设置函数闭包环境

2024-05-17 16:31:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我想动态声明一个函数,我想包装对全局变量的任何访问,或者定义哪些变量是自由的,并包装对自由变量的任何访问。在

我在玩这样的代码:

class D:
    def __init__(self):
        self.d = {}     
    def __getitem__(self, k):
        print "D get", k
        return self.d[k]
    def __setitem__(self, k, v):
        print "D set", k, v
        self.d[k] = v
    def __getattr__(self, k):
        print "D attr", k
        raise AttributeError

globalsDict = D()

src = "def foo(): print x"

compiled = compile(src, "<foo>", "exec")
exec compiled in {}, globalsDict

f = globalsDict["foo"]
print(f)

f()

这将产生输出:

^{pr2}$

我想要的是用类似dict的包装器D捕捉对x的访问。我怎么能做到呢?在

我不想预先定义所有全局变量(在本例中是x),因为我希望能够延迟地加载它们。在


Tags: 函数代码selfsrc声明定义foodef
2条回答

试试这个

class GlobalDict(object):

    def __init__(self, **kwargs):
        self.d = kwargs

    def __getitem__(self, key):
        print 'getting', key
        return self.d[key]

    def __setitem__(self, key, value):
        print 'setting', key, 'to', value
        if hasattr(value, '__globals__'):
            value.__globals__.update(self.d)
        self.d[key] = value
        for v in self.d.values():
            if v is not value:
                if hasattr(v, '__globals__'):
                    v.__globals__.update(self.d)

    def __delitem__(self, key):
        print 'deling', key
        del self.d[key]
        for v in self.d.values():
            if hasattr(v, '__globals__'):
                del v.__globals__[key]

>>> gd = GlobalDict()
>>> src = 'def foo(): print x'
>>> compiled = compile(src, '<foo>', 'exec')
>>> exec compiled in {}, gd
setting foo to <function foo at 0x102223b18>
>>> f = gd['foo']
getting foo
>>> f
<function foo at 0x102223b18>
>>> f() # This one will throw an error
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<foo>", line 1, in foo
NameError: global name 'x' is not defined
>>> gd['x'] = 1
setting x to 1
>>> f()
1
>>> del gd['x'] # removes 'x' from the globals of anything in gd
>>> f() # Will now fail again
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<foo>", line 1, in foo
NameError: global name 'x' is not defined

您需要的是对象代理。在

下面是一个支持调用前和调用后挂钩的对象代理的方法:

http://code.activestate.com/recipes/366254-generic-proxy-object-with-beforeafter-method-hooks/

创建一个子类,直到第一次调用_pre钩子时才实际加载对象。任何访问对象的操作都会导致加载实际对象,所有调用都将显示为由实际对象直接处理。在

相关问题 更多 >