7

関数を動的に宣言し、グローバル変数へのアクセスをラップしたい、または代わりに、どの変数がフリーであるかを定義し、フリー変数へのアクセスをラップしたい。

私は次のようなコードで遊んでいます:

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()

これにより、次の出力が生成されます。

D set foo <function foo at 0x10f47b758>
D get foo
<function foo at 0x10f47b758>
Traceback (most recent call last):
  File "test_eval.py", line 40, in <module>
    f()
  File "<foo>", line 1, in foo
NameError: global name 'x' is not defined

私が欲しいのは、どういうわけかx私のdictのようなラッパーでアクセスをキャッチすることDです。どうやってやるの?

すべてのグローバル変数(この場合)を事前に定義したくないのは、xそれらを遅延してロードできるようにするためです。

4

2 に答える 2

2

あなたが探しているのはobject proxyingです。

呼び出し前および呼び出し後のフックをサポートするオブジェクト プロキシのレシピを次に示します。

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

_preフックが最初に呼び出されるまで実際にオブジェクトをロードしないサブクラスを作成します。オブジェクトにアクセスすると、実際のオブジェクトが読み込まれ、すべての呼び出しが実際のオブジェクトによって直接処理されているように見えます。

于 2011-07-22T18:58:03.947 に答える
1

これを試してみてください

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
于 2011-07-22T17:34:38.220 に答える