python - 多个 python 装饰器检索原始函数

标签 python decorator

我有一个运行检查的类,每个函数执行一次检查。我想过装饰器添加额外的条件,但这可能并不明智。

我理解装饰器的概念,每个装饰器都将其装饰的函数作为输入并返回到下一个装饰的函数。这对于返回字符串的函数来说效果很好,因为输出可以很容易地由装饰器编辑并返回给下一个装饰器。

我想做的是修改函数属性,例如放置一个 don't exec 标志来表示不运行检查,require auth 表示仅在以下情况下执行的检查已授予身份验证,或更改函数属性 order,以顺序检查启动。

# I return f only if is_authenticated flag is True
def auth_required(is_authenticated):
    def check_authentication(f):
        if is_authenticated:
            return f
    return check_authentication

# I edit order variable
def assignOrder(order):
    def do_assignment(f):
        f.order = order
        return f
    return do_assignment
# I instanciate Checks class and provide authentication;
# login and password will be tried and is_authenticat flag set accordingly
c = Checks(target, login, password)

# I sort on order variable and launch checks
functions = sorted(
    [
        getattr(c, field) for field in dir(c)
        if hasattr(getattr(c, field), 'order')
    ],key = (lambda field : field.order) 
)
for function in functions:
    function()

# I assign decorators so that order variable is set 
# I would like auth_required triggers launch if auth is performed
@auth_required(True)
@assignOrder(100)
def check_shares(self):
    # check defined here

这对 assignOrder 非常有用,我的检查以正确的顺序启动。

但是 @auth_required 应用于 assignOrder 这不是我想要的。

有没有办法找回要装饰的原始函数?或者装饰器的使用在这种情况下不相关?解决方案是什么?

非常感谢

最佳答案

没有解决问题的通用方法。装饰器没有内置的协作工具,甚至不需要保留对原始函数的引用。

所以你需要自己想出一个协议(protocol),例如使 assignOrder 将原始函数保存到 do_assignment

然后在 is_authenticated 中,你必须查看传递的函数背后是否有一个“真正的”函数,然后使用它。

关于python - 多个 python 装饰器检索原始函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30639854/

相关文章:

computer-science - 装饰器,属性,方面和特质有什么区别?

python - 根据django查询中的列值进行计数和排序

python - 调整 Python Regex 以在 findall 结果中不包含单个数字

python - 如何将此 "Python+twill+mechanize"组合部署到 "Google App Engine"?

python - 当我在 Python 解释器中键入函数名称时,会返回哪些信息?

python - 装饰器在它装饰的函数被调用之前运行?

python - 使用 pandas 和 fuzzwuzzy 匹配相似的列元素

python - PyEphem 中 ephem.date(...) 和 ephem.Date(...) 的区别

python - 将参数传递给装饰器,用于装饰类方法

c++ - 结构化对象的高性能装饰器模式