【发布时间】:2012-05-23 13:26:50
【问题描述】:
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
【问题讨论】:
-
如果您在装饰器和注释方面需要更多帮助,请在此处查看我的博客文章。 blog.mattalcock.com/2013/1/5/decorates-and-annotations