【问题标题】:UnboundLocalError: Decorator with default parametersUnboundLocalError:具有默认参数的装饰器
【发布时间】:2011-04-12 04:25:32
【问题描述】:

这是我的装饰器代码。由于某种原因,我收到 UnboundLocalError 但我找不到它。

>>> def validate(schema=None):
        def wrap(f):
            def _f(*args, **kwargs):
                if not schema:
                schema = f.__name__
            print schema
            return f()
            return _f
        return wrap

>>> @validate()
    def some_function():
        print 'some function'


>>> some_function()
Traceback (most recent call last):
  File "<pyshell#27>", line 1, in <module>
    some_function()
  File "<pyshell#22>", line 4, in _f
    if not schema:
UnboundLocalError: local variable 'schema' referenced before assignment
>>> 

所以,我想也许最好在这里发帖。我可能遗漏了什么。

谢谢。

【问题讨论】:

  • 你的完整回溯在哪里???

标签: python decorator


【解决方案1】:

编译器无法确定schema 的正确范围。在_f() 中使用nonlocal schema (3.x) 或稍微更改_f() 的定义:

def _f(self, schema=schema, *args, **kwargs):

【讨论】:

  • 嗨,伊格纳西奥。非本地模式是什么意思?
  • 我的意思是nonlocal这个词,后面是一个空格,然后是schema这个词。 python.org/dev/peps/pep-3104
  • 感谢伊格纳西奥,它有效!我没有使用 3.x。这是使它在 2.x 中工作的唯一方法吗?
  • 是的。编译器不会生成字节码来查看外部范围,因为你分配给它,所以你必须强制它在本地范围内。
  • 那个装饰器从不分配给reason
猜你喜欢
  • 1970-01-01
  • 2016-09-27
  • 2023-02-10
  • 2015-10-22
  • 2021-12-16
  • 2023-03-31
  • 1970-01-01
  • 2019-11-07
  • 2014-07-21
相关资源
最近更新 更多