我想做一个@pure
Python 的装饰器,其中一部分是能够有选择地禁止访问函数的全局范围。
有没有一种方法可以以编程方式更改哪个字典事物充当函数的全局/外部作用域?
因此,例如在下面我希望能够拦截对f
in h
并抛出错误,但我想允许访问g
因为它是一个纯函数。
def f():
print("Non-pure function")
@pure
def g(i):
return i + 1
@pure
def h(i):
f()
return g(i)
你必须创建一个new旧函数对象:
newfunc = type(h)(h.__code__, cleaned_globals, h.__name__, h.__defaults__, h.__closure__)
Here, cleaned_globals
是一个字典,用作新创建的函数对象的全局命名空间。所有其他参数都与原始函数相呼应。
cleaned_globals
可以基于以下副本h.__globals__
, 当然。
Demo:
>>> def h(i):
... f()
... return g(i)
...
>>> def g(i):
... return i + 1
...
>>> def f():
... print("Non-pure function")
...
>>> h(1)
Non-pure function
2
>>> cleaned_globals = {'g': g}
>>> newfunc = type(h)(h.__code__, cleaned_globals, h.__name__, h.__defaults__, h.__closure__)
>>> newfunc(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in h
NameError: global name 'f' is not defined
>>> cleaned_globals['f'] = lambda: print('Injected function')
>>> newfunc(1)
Injected function
2
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)