Browse topics

Decorators and functools.wraps

Version
3.14
Review
Draft

Summary#

A decorator is a callable applied to a function when it is defined. Its return value is bound to the function name. functools.wraps copies metadata such as the name and docstring onto a wrapper function.

Syntax#

python
@decorator
def first():
    pass

@factory(argument)
def second():
    pass

Example#

python
from functools import wraps


def repeat(times):
    def decorate(function):
        @wraps(function)
        def wrapper(*args, **kwargs):
            return [function(*args, **kwargs) for _ in range(times)]

        return wrapper

    return decorate


@repeat(times=2)
def greet(name):
    """Return a greeting."""
    return f"hello {name}"


print(greet("Sam"))
print(greet.__name__, "-", greet.__doc__)
print(greet.__wrapped__("Kim"))

Expected output#

Text
['hello Sam', 'hello Sam']
greet - Return a greeting.
hello Kim

Common mistakes#

A decorator factory must be called. Writing @repeat here passes the function as times and binds the name to decorate instead of a working wrapper. Return the intended result explicitly from the wrapper. Here that result is a list of the individual return values.

Version applicability#

Both decorator forms in Syntax work on all Python 3 releases. wraps has set __wrapped__ since Python 3.2. The example requires 3.6 for the f-string. Python 3.9 relaxed the grammar to allow arbitrary expressions after @.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0