A decorator is a function that takes another function and returns an enhanced version of it. It lets you add behaviour — logging, timing, caching, access checks — around a function without touching its code. The @ syntax makes it clean.
The core idea
@decorator above a function is just shorthand for func = decorator(func). The decorator wraps the original in a new function (a closure) that does something extra before/after calling it:
import timefrom functools import wrapsdef timed(func):@wraps(func) # preserve func's name/docstringdef wrapper(*args, **kwargs):start = time.time()result = func(*args, **kwargs) # call the real functionprint(f"{func.__name__} took {time.time() - start:.3f}s")return resultreturn wrapper@timeddef slow():time.sleep(0.5)slow() # runs slow() AND prints its timing
Why @wraps matters
Built-in decorators
You'll meet decorators everywhere — several ship with Python or frameworks:
from functools import lru_cache@lru_cache # caches results — instant repeat callsdef fib(n):return n if n < 2 else fib(n-1) + fib(n-2)# @property, @staticmethod, @classmethod (OOP module)# @app.route("/") in Flask, @pytest.fixture in tests…
Key takeaways
- 01A decorator wraps a function to add behaviour without editing it.
- 02@decorator is shorthand for func = decorator(func).
- 03The wrapper is a closure that calls the original with *args/**kwargs.
- 04Always use functools.wraps to preserve the original name and docstring.
- 05Common uses: logging, timing, caching (lru_cache), auth, route registration.
