What are decorators in Python and how do they work?
- Technology:
- Python
Quick answer
A decorator is a function that takes another function and returns a modified version of it, letting you add behaviour such as logging, caching or access control without changing the original code.
Detailed explanation
The @decorator syntax is shorthand for func = decorator(func). A typical decorator defines an inner wrapper function that runs code before and after calling the original function, and returns that wrapper. Use functools.wraps so the wrapped function keeps its name and docstring.
Decorators rely on functions being first-class objects and on closures. Common built-in ones include @property, @staticmethod, @classmethod and functools.lru_cache. Frameworks use them heavily, for example @app.route("/") in Flask.
Example
import functools, time
def timed(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
print(f"{func.__name__} took {time.perf_counter() - start:.3f}s")
return result
return wrapper
@timed
def load_data():
...