检查是否用特定的装饰器装饰了Python函数

Jor*_*alo 3 python-2.7 python-decorators

我想检查是否装饰了Python函数,并将decorator参数存储在函数dict中。这是我的代码:

from functools import wraps

def applies_to(segment="all"):
    def applies(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            func.func_dict["segment"] = segment
            print func.__name__
            print func.func_dict
            return func(*args, **kwargs)
        return wrapper
    return applies
Run Code Online (Sandbox Code Playgroud)

但是看起来该字典丢失了:

@applies_to(segment="mysegment")
def foo():
    print "Some function"


> foo() # --> Ok, I get the expected result
foo
{'segment': 'mysegment'}

> foo.__dict__ # --> Here I get empty result. Why is the dict empty?
{}
Run Code Online (Sandbox Code Playgroud)

Jor*_*alo 5

好的,多亏了user2357112的线索,我找到了答案。即使有所改善

from functools import wraps

def applies_to(*segments):
    def applies(func):
        func.func_dict["segments"] = list(segments)
        @wraps(func)
        def wrapper(*args, **kwargs):
            return func(*args, **kwargs)
        return wrapper
    return applies
Run Code Online (Sandbox Code Playgroud)

谢谢!