简体   繁体   English

无法在装饰器内设置 function 属性

[英]Cannot set function attribute inside a decorator

I have a Python code like this:我有这样的 Python 代码:

from functools import wraps

def dec(f): 
    
    @wraps(f)
    def wrapper(*args, **kwargs):
        f.foo = 'foo'
        value = f()
        f.foo = 'foo'
        return value
    return wrapper

@dec
def f():
    print('Hello, f')

f()
print(f.foo)

You can find the ready code here :你可以在这里找到现成的代码:

The problem with this code is that I end up with AttributeError: 'function' object has no attribute 'foo' , although I use wraps decorator from functools which should preserve the attribute scope of the function.这段代码的问题是我最终得到AttributeError: 'function' object has no attribute 'foo' ,尽管我使用了 functools 的wraps装饰器,它应该保留 ZC1C425268E68394F14AB57A 的属性 scope Any ideas what the cause of the error is?任何想法错误的原因是什么?

You're setting the attribute on f , but you're returning wrapper and the f in the main scope is that wrapper function object.您在f上设置属性,但您正在返回wrapper ,主 scope 中的fwrapper function object。 To illustrate with less confusing names:用不太容易混淆的名称来说明:

def dec(f): 
    @wraps(f)
    def wrapper(*args, **kwargs):
        f.foo = 'foo'  # <-- this is the original bar function
        value = f()
        return value

    return wrapper

@dec
def bar():
    print('Hello, f')

bar()  # <-- this is wrapper()

When you change your code to wrapper.foo = 'foo' , it works as expected.当您将代码更改为wrapper.foo = 'foo'时,它会按预期工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM