
[英]Why does the UnboundLocalError occur on the second variable of the flat comprehension?
[英]Why is this variable creating an UnboundLocalError?
我正在尝试创建一个包装器,它使用 function 名称和 arguments 的字符串表示来创建缓存密钥。
我已经尝试了以下方法,由于某种原因我得到了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
我很困惑,我错过了什么。 这似乎是一个基本的愚蠢错误,或者是我不知道的装饰器的一些行为。
key
不是全局的; 它是nonlocal ,在cache_key_gen
中定义。
def cache_key_gen(func):
... key = func.__name__
... def wrapper(*args):
... nonlocal key
... print(key)
... for arg in args:
... key += str(arg)
... print(key)
... return func(*args)
... return wrapper
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.