【问题标题】:How to check if a function is decorated with a specific decorator?如何检查函数是否用特定的装饰器装饰?
【发布时间】:2018-01-12 22:42:52
【问题描述】:

我想检查一个 Python 函数是否被修饰,并将修饰器参数存储在函数 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

但看起来字典丢失了:

@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?
{}

【问题讨论】:

  • 你在错误的时间修改了错误的函数。
  • 我应该在运行时修改“应用”函数吗?

标签: python python-decorators


【解决方案1】:

好的,感谢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

谢谢!

【讨论】:

    猜你喜欢
    • 2011-07-26
    • 2019-02-11
    • 1970-01-01
    • 2021-04-19
    • 1970-01-01
    • 2021-04-14
    • 2017-08-27
    • 2015-05-27
    • 2019-07-29
    相关资源
    最近更新 更多