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
しかし、それは非常に冗長です。引数を受け入れるデコレータを書きやすくするショートカットはありますか?
注: ネストされた 3 つの関数を使用して、引数付きのデコレータを実装することも可能であることは認識していますが、それも少し最適ではないように感じます。
たとえば、@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