Python:编写接受参数的装饰器的快捷方式?

标签 python decorator

Python 标准库是否有编写接受参数的装饰器的快捷方式?

例如,如果我想写一个像with_timeout(timeout)这样的装饰器:

@with_timeout(10.0)
def cook_eggs(eggs):
    while not eggs.are_done():
        eggs.cook()

我必须写这样的东西:

def with_timeout(timeout):
    _func = [None]
    def with_timeout_helper(*args, **kwargs):
        with Timeout(timeout):
            return _func[0](*args, **kwargs)
    def with_timeout_return(f):
        return functools.wraps(f)(with_timeout_helper)
    return with_timeout_return

但这太冗长了。有没有捷径可以让接受参数的装饰器更容易编写?

注意:我意识到也可以使用三个嵌套函数来实现带参数的装饰器……但这感觉也有点次优。

例如,可能类似于 @decorator_with_arguments 函数:

@decorator_with_arguments
def timeout(f, timeout):
    @functools.wraps(f)
    def timeout_helper(*args, **kwargs):
        with Timeout(timeout):
            return f(*args, **kwargs)
    return timeout_helper

最佳答案

老实说,我倾向于将我的装饰器写成类

class TestWithArgs(object):
    def __init__(self, *deco_args, **deco_kwargs):
        self.deco_args = deco_args
        self.deco_kwargs = deco_kwargs
    def __call__(self, func):
        def _wrap(self, *args, **kwargs):
            print "Blah blah blah"
            return func(*args, **kwargs)
        return _wrap

如果不是稍微清晰一点就没什么了

关于Python:编写接受参数的装饰器的快捷方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10610824/

相关文章:

python - 如何将默认时间(但不是日期)添加到 DJango 中的 DateTimeField?

angularjs - 在 Jasmine 测试中模拟 AngularJS $httpBackend 并使用装饰器时出现 "$httpBackend.when is not a function"错误

python - 装饰师的工作

java - 向任何 java 异常添加属性

python - python 抓取和剥 ionic 标签

python - NumPy 根据另一个数组中的值对第三个数组中的每个匹配元素求和一个数组

python - 将 pandas 数据框保存为图像或 pdf 文档中的表格,并具有良好的多索引显示

module - 如何从特定模块创建所有装饰函数的向量?

python - Pydev 显示 @staticmethod 重新实现的错误

python - 使用 pymupdf-page.searchFor() 选择精确匹配