Decorators in Python — a practical guide to Python decorators with clear examples you can reuse in real projects.
Python Tutorial Series (54/95). Prefer one article? Read the complete Python tutorial.
Short description
A decorator takes a function and returns a new function. Use `@decorator` syntactic sugar.
Simple decorator
def log(fn):
def wrapper(*args, **kwargs):
print('calling', fn.__name__)
return fn(*args, **kwargs)
return wrapper
@log
def add(a, b):
return a + b
print(add(2, 3))