首页 > 解决方案 > 也可以用作独立函数的 Python 装饰器

问题描述

我对装饰器很陌生,我正在尝试构建一个带有参数的装饰器,该参数既可以作为装饰器,也可以作为独立函数使用。基本思想是在不满足某些条件时引发错误。例子:

ensure_condition("fail") # exception should be raised
ensure_condition("pass") # nothing should happen

@ensure_condition("fail") # check condition before every `func` call
def f1():
    return 1

我想过这样做:

def ensure_condition(arg: str):
    if not _validate(arg):
        raise Exception("failed")

    def ensure_condition_decorator(f = lambda *_: None):
        def wrapper(*args, **kwargs):
            return f(*args, **kwargs)

        return wrapper

    return ensure_condition_decorator

但是上面的结果在函数被声明(不仅仅是执行)_validate时也会被调用。f1

还有其他想法吗?

谢谢!

标签: pythondecoratorpython-decorators

解决方案


推荐阅读