有没有办法写一个装饰器,以便以下工作?
assert 'z' not in globals()
@my_decorator
def func(x, y):
print z
Run Code Online (Sandbox Code Playgroud)
编辑:从anwser搬来
回答hop的"为什么?":语法糖/ DRY.
它不是关于缓存,而是基于x和y的值计算z(和z1,z2,z3,...).
我有很多相关的功能,我不想写
z1, z2, z3=calculate_from(x, y)
Run Code Online (Sandbox Code Playgroud)
在每个单一功能的开头 - 我会在某处弄错.如果这是c我用cpp做这个(如果这是lisp,我会用宏来做...),但我想看看装饰者是否可以做同样的事情.
如果它有帮助,我几乎肯定会将装饰器称为"precalculate_z",它肯定不会成为任何公共API的一部分.
我也许可以通过使用类基础结构获得类似的效果,但我想看看它是否可以用于原始函数.
Aar*_*ron 11
回应Hop的答案
Python没有动态范围的变量,但您可以模拟它.这是一个通过创建全局绑定来模拟它的示例,但在退出时恢复以前的值:
def adds_dynamic_z_decorator(f):
def replacement(*arg,**karg):
# create a new 'z' binding in globals, saving previous
if 'z' in globals():
oldZ = (globals()['z'],)
else:
oldZ = None
try:
globals()['z'] = None
#invoke the original function
res = f(*arg, **karg)
finally:
#restore any old bindings
if oldZ:
globals()['z'] = oldZ[0]
else:
del(globals()['z'])
return res
return replacement
@adds_dynamic_z_decorator
def func(x,y):
print z
def other_recurse(x):
global z
print 'x=%s, z=%s' %(x,z)
recurse(x+1)
print 'x=%s, z=%s' %(x,z)
@adds_dynamic_z_decorator
def recurse(x=0):
global z
z = x
if x < 3:
other_recurse(x)
print 'calling func(1,2)'
func(1,2)
print 'calling recurse()'
recurse()
Run Code Online (Sandbox Code Playgroud)
我对上述代码的实用性或完整性不作任何保证.实际上,我保证它是疯了,你应该避免使用它,除非你想从你的Python同行鞭打.
这段代码类似于eduffy和John Montgomery的代码,但确保'z'被创建并正确恢复"就像"局部变量一样 - 例如,注意'other_recurse'如何能够看到'z的绑定' '在'递归'的主体中指明.
我不知道本地范围,但您可以暂时提供替代的全局名称空间.就像是:
import types
def my_decorator(fn):
def decorated(*args,**kw):
my_globals={}
my_globals.update(globals())
my_globals['z']='value of z'
call_fn=types.FunctionType(fn.func_code,my_globals)
return call_fn(*args,**kw)
return decorated
@my_decorator
def func(x, y):
print z
func(0,1)
哪个应该打印"z的值"