My decorator is "closure-style"; it does some work before returning the decorated function.
Borrowing from this famous question: Preserving signatures of decorated functions
def args_as_ints(f):
time.sleep(1) # hard at work
def g(*args, **kwargs):
args = [int(x) for x in args]
kwargs = dict((k, int(v)) for k, v in kwargs.items())
return f(*args, **kwargs)
return g
functools.wraps
does not preserve the signature in Python 2.
from functools import wraps
def args_as_ints(f):
time.sleep(1) # hard at work
@wraps(f)
def g(*args, **kwargs):
args = [int(x) for x in args]
kwargs = dict((k, int(v)) for k, v in kwargs.items())
return f(*args, **kwargs)
return g
@args_as_ints
def funny_function(x, y, z=3):
"""Computes x*y + 2*z"""
return x*y + 2*z
help(funny_function)
shows
Help on function funny_function in module __main__:
funny_function(*args, **kwargs)
Computes x*y + 2*z
The decorator
module doesn't seem to support this style of decorator.
Also related: Preserve Signature in Decorator python 2