Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

decorator module vs functools.wraps

The functionality of the decorator module and functools.wraps is closely related. What are the differences between the two (as of Python 3.3 / 3.4)?

I am aware of one difference: 3+ years ago, decorator supported help, while wraps didn't (see also this).

like image 305
max Avatar asked Dec 17 '12 02:12

max


2 Answers

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.

like image 195
BrenBarn Avatar answered Nov 15 '22 16:11

BrenBarn


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.

like image 33
chtenb Avatar answered Nov 15 '22 16:11

chtenb