Decorators and reusable wrappers
3.15.2
Wrap a function to add reusable behavior and preserve useful function metadata.
On this page
Wrap a call with a decorator
A decorator takes a function and returns a replacement callable. @announce applies the decorator when Python defines the function. The wrapper forwards arguments and returns the original result. functools.wraps keeps metadata such as the name and documentation.
from functools import wraps
def announce(function):
@wraps(function)
def wrapped(*args, **kwargs):
print("Running", function.__name__)
return function(*args, **kwargs)
return wrapped
@announce
def total(quantity, price):
return quantity * price
print(total(2, 3.5), total.__name__)
Example output
Running total 7.0 total
Use context managers for cleanup
A with block ties setup and cleanup to a scope. Use contextlib.contextmanager to express setup before yield and cleanup in finally. This is useful for files, transactions, temporary directories, and measured sections of code.
from contextlib import contextmanager
@contextmanager
def operation():
print("open")
try:
yield "ready"
finally:
print("close")
with operation() as status:
print(status)
Example output
open ready close