Functions

Decorators

Decorators wrap or register functions using @ syntax.

A decorator is just a function that takes a function and returns another callable. Applying it manually shows the wrapping step.

Source

from functools import wraps


def loud(func):
    @wraps(func)
    def wrapper(name):
        return func(name).upper()
    return wrapper


def greet(name):
    return f"hello {name}"

manual_greet = loud(greet)
print(manual_greet("python"))

Output

HELLO PYTHON
BEFOREfFNf₀AFTER @DECfwrapperf₀
@dec rebinds the name to wrapper(f₀); the original function survives only in the wrapper's closure cell.

The @loud syntax performs the same rebinding at definition time. After decoration, welcome refers to the wrapper returned by loud.

Source

@loud
def welcome(name):
    """Return a welcome message."""
    return f"welcome {name}"

print(welcome("workers"))

Output

WELCOME WORKERS

functools.wraps copies useful metadata from the original function onto the wrapper.

Source

print(welcome.__name__)
print(welcome.__doc__)

Output

welcome
Return a welcome message.

Notes

See also

Run the complete example

Example code

Expected output

HELLO PYTHON
WELCOME WORKERS
welcome

Execution time appears here after you run the example.