【问题标题】:Why is this variable creating an UnboundLocalError?为什么这个变量会创建 UnboundLocalError?
【发布时间】: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


    【解决方案1】:

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-03
      • 1970-01-01
      • 2011-09-04
      相关资源
      最近更新 更多