Skip to main content
Albero Academy

Decorators

Wrap a function to add behaviour — logging, timing, caching — without changing it.

Functions12 min

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:

a timing decorator
import time
from functools import wraps
def timed(func):
@wraps(func) # preserve func's name/docstring
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs) # call the real function
print(f"{func.__name__} took {time.time() - start:.3f}s")
return result
return wrapper
@timed
def 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:

common decorators
from functools import lru_cache
@lru_cache # caches results — instant repeat calls
def 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

  1. 01A decorator wraps a function to add behaviour without editing it.
  2. 02@decorator is shorthand for func = decorator(func).
  3. 03The wrapper is a closure that calls the original with *args/**kwargs.
  4. 04Always use functools.wraps to preserve the original name and docstring.
  5. 05Common uses: logging, timing, caching (lru_cache), auth, route registration.

Finished this chapter?

Mark it complete to track your progress through Python.