Functions
Decorators
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 PYTHONThe @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 WORKERSfunctools.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
@decoratoris shorthand for assigningfunc = decorator(func).- Decorators can wrap, replace, or register functions.
- Use
functools.wrapsin production wrappers that should preserve metadata.
See also
- related: Closures
- related: Functions
- next depth: Callable Types
- next depth: Classmethods and Staticmethods
Run the complete example
Expected output
HELLO PYTHON
WELCOME WORKERS
welcome
Execution time appears here after you run the example.