【发布时间】:2021-02-17 13:56:17
【问题描述】:
我正在尝试创建一个包装器,它使用函数名和参数的字符串表示来创建缓存键。
我尝试了以下方法,但由于某种原因得到NameError
>>> def cache_key_gen(func):
... key = func.__name__
... def wrapper(*args):
... global key
... print(key)
... for arg in args:
... key += str(arg)
... print(key)
... return func(*args)
... return wrapper
...
>>> @cache_key_gen
... def add(x, y):
... return x + y
...
>>> add(1,2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in wrapper
NameError: name 'key' is not defined
当我尝试以下操作时,我收到了UnboundLocalError
>>> def cache_key_gen(func):
... key = func.__name__
... def wrapper(*args):
... for arg in args:
... key += str(arg)
... print(key)
... return func(*args)
... return wrapper
...
>>> @cache_key_gen
... def add(x, y):
... return x + y
...
>>> add(1,2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in wrapper
UnboundLocalError: local variable 'key' referenced before assignment
我很困惑,我错过了什么。这似乎是一个基本的愚蠢错误,或者是我不知道的装饰器的一些行为。
【问题讨论】:
标签: python caching python-decorators