About Preserving Decorated Function Names and Docstrings

Use the functools.wraps decorator when creating function decorators in Python to preserve decorated function names, docstrings, and argument lists:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
from functools import wraps

def verbose(func):

    @wraps(func)
    def with_verbose_output(*args, **kwargs):
        print(f"Calling {func.__name__}()…")
        return func(*args, **kwargs)

    return with_verbose_output

@verbose
def add(x, y):
    """Adds two numbers"""
    return x + y

print(add.__name__)
print(add.__doc__)

Tips and Tricks Programming Python 3