La libreria standard Python ha una scorciatoia per scrivere decoratori che accettano argomenti?Python: scorciatoia per scrivere decoratori che accettano argomenti?
Per esempio, se voglio scrivere un decoratore come with_timeout(timeout)
:
@with_timeout(10.0)
def cook_eggs(eggs):
while not eggs.are_done():
eggs.cook()
devo scrivere qualcosa di simile a:
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
Ma questo è terribilmente prolisso. C'è una scorciatoia che rende i decoratori che accettano argomenti più facili da scrivere?
Nota: Mi rendo conto che è anche possibile utilizzare tre funzioni annidate per implementare decoratori con argomenti ... Ma che si sente solo un po 'troppo non ottimale.
Per esempio, forse qualcosa di simile a una funzione @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
Se avete bisogno di più aiuto decoratori e annotazioni vedere il mio post sul blog qui. http://blog.mattalcock.com/2013/1/5/decorates-and-annotations/ –