decorator module vs functools.wraps
Per the discussion with BrenBarn, nowadays functools.wraps
also preserves the signature of the wrapped function. IMHO this makes the decorator
decorator almost obsolete.
from inspect import signature
from functools import wraps
def dec(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
def dec2(func):
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
def foo(a: int, b):
pass
print(signature(dec(foo)))
print(signature(dec2(foo)))
# Prints:
# (*args, **kwargs)
# (a:int, b)
Note that one has to use signature
and not getargspec
. Tested with python 3.4.
One of the main differences is listed right in the documentation you linked to: decorator
preserves the signature of the wrapped function, while wraps
does not.