装饰器中的参数在装饰器范围中不可用?

时间:2020-02-06 18:03:38

标签: python-3.x python-decorators

我有一个这样的装饰器:

def dec(default):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            default = default or ['abc']
            return func(*args, **kwargs)
        return wrapper
    return decorator

# use:
# decor = dec(default=['123'])
# @decor
# def something(default...

所以我得到了这个错误,实际上,我的短毛猫在运行代码之前就把它给了我,但是我也在测试中得到了它:

local variable 'default' defined in enclosing scope on line x referenced before assignment

我在此装饰器中做错了什么,导致无法在包装器内使用外部参数?

我是否必须在*args, **kwargs之前将其显式传递给包装器?如果我不调用装饰器函数本身就返回该怎么办? return decorator

我可以找到的其他示例似乎没有这个问题(How to build a decorator with optional parameters?

这是Python 3的东西吗?这些示例主要是python2。也许在py3中,我必须将它们明确定义为global default

@wraps的原因,不是吗?我发现此示例似乎工作正常,但未使用@wraps。尽管我需要使用它。

def d(msg=None):
    def decorator(func):
        def newfn():
            msg = msg or 'abc'
            return func()
        return newfn
    return decorator

@d('This is working')
def hello():
    print 'hello world !'

@d()
def hello2():
    print 'also hello world'

我该怎么办?

0 个答案:

没有答案