Python Decorators
Decorators are one of Python's most elegant features — they let you
wrap a function (or class) with additional behaviour without modifying its source code. The @decorator syntax is used everywhere in Python frameworks: Django's @login_required, FastAPI's @app.get(),
Flask's @app.route(), Python's own @property, @staticmethod, and @classmethod. This chapter builds decorators from the ground up — from
first-principles function wrapping all the way to decorators with arguments, class decorators, and
professional production patterns.
First-Class Functions — The Foundation
Decorators are built on one core fact: Python functions are first-class objects. They can be stored in variables, passed as arguments, returned from functions, and stored in data structures. This makes higher-order functions (and decorators) possible.
# Functions are objects — store, pass, return them
def greet(name):
return f"Hello, {name}!"
# Assign to a variable
say_hi = greet
print(say_hi("Alice")) # Hello, Alice!
# Pass as argument
def apply(func, value):
return func(value)
print(apply(greet, "Bob")) # Hello, Bob!
print(apply(str.upper, "hi")) # HI
# Return from a function — closure
def make_multiplier(n):
def multiplier(x):
return x * n # 'n' is captured from outer scope
return multiplier # return the inner function
double = make_multiplier(2)
triple = make_multiplier(3)
print(double(5)) # 10
print(triple(5)) # 15
# Functions stored in collections
operations = {
"double": lambda x: x * 2,
"square": lambda x: x ** 2,
"negate": lambda x: -x,
}
print(operations["square"](4)) # 16
Building a Decorator from Scratch
A decorator is a function that takes a function, wraps it in a new function with added
behaviour, and returns the new function. The @decorator syntax is just
shorthand for func = decorator(func).
# ── Step 1: Manual wrapping (no @ syntax) ────────────
def add_banner(func): # decorator function
def wrapper(): # inner wrapper
print("=" * 20)
func() # call original function
print("=" * 20)
return wrapper # return wrapper, not func()
def say_hello():
print("Hello from K2infocom!")
# Apply manually
say_hello = add_banner(say_hello) # wrap it
say_hello()
# ====================
# Hello from K2infocom!
# ====================
# ── Step 2: @ syntax sugar ────────────────────────────
@add_banner # ← identical to say_hello = add_banner(say_hello)
def say_hello():
print("Hello from K2infocom!")
say_hello() # same output as above
# ── Verify what happened ─────────────────────────────
print(say_hello) # <function add_banner.<locals>.wrapper>
print(say_hello.__name__) # wrapper ← NOT say_hello! (fix with wraps)
functools.wraps — Preserving Function Identity
Without functools.wraps, the decorated function
loses its __name__, __doc__, and __module__ — they become the wrapper's attributes. This breaks debugging,
documentation, and tools like logging. Always use @functools.wraps(func)
on your wrapper.
import functools
# ── Without @wraps — broken identity ─────────────────
def bad_decorator(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@bad_decorator
def greet(name):
"""Return a greeting."""
return f"Hello, {name}!"
print(greet.__name__) # 'wrapper' ← WRONG!
print(greet.__doc__) # None ← docstring lost!
# ── With @wraps — identity preserved ─────────────────
def good_decorator(func):
@functools.wraps(func) # ← copies __name__, __doc__, __module__, etc.
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@good_decorator
def greet(name):
"""Return a greeting."""
return f"Hello, {name}!"
print(greet.__name__) # 'greet' ← correct!
print(greet.__doc__) # 'Return a greeting.'
print(greet.__wrapped__) # original function — for introspection
# ── Template: the correct minimal decorator ───────────
def my_decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
# --- before ---
result = func(*args, **kwargs)
# --- after ---
return result
return wrapper
Decorators with *args and **kwargs
A general-purpose decorator must accept any function signature. Use *args and **kwargs in the wrapper so it
can wrap functions with any number and type of arguments.
import functools
import time
# ── Timer decorator — works on any function ───────────
def timer(func):
@functools.wraps(func)
def wrapper(*args, **kwargs): # accept any signature
start = time.perf_counter()
result = func(*args, **kwargs) # forward all arguments
end = time.perf_counter()
print(f"{func.__name__} took {end - start:.4f}s")
return result # return original result
return wrapper
@timer
def no_args():
time.sleep(0.01)
@timer
def with_args(n, power=2):
return sum(i**power for i in range(n))
no_args() # no_args took 0.0101s
print(with_args(10000, power=3)) # with_args took 0.0012s → result
# ── Logger decorator ──────────────────────────────────
import logging
logging.basicConfig(level=logging.INFO)
def log_call(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
logging.info(f"CALL {func.__name__}({args}, {kwargs})")
try:
result = func(*args, **kwargs)
logging.info(f"RETURN {func.__name__} → {result!r}")
return result
except Exception as e:
logging.error(f"ERROR {func.__name__}: {e}")
raise
return wrapper
@log_call
def add(a, b): return a + b
add(3, 4) # INFO: CALL add((3, 4), {}) → INFO: RETURN add → 7
Decorator Factories — Decorators with Arguments
What if your decorator needs configuration? Use a decorator factory — a function that accepts arguments and returns a decorator. This adds an extra layer of nesting: factory → decorator → wrapper.
import functools
import time
# ── repeat(n) — run a function n times ────────────────
def repeat(times): # factory: accepts argument
def decorator(func): # real decorator: accepts function
@functools.wraps(func)
def wrapper(*args, **kwargs):
result = None
for _ in range(times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(3) # ← calls repeat(3) first, uses returned decorator
def say(msg):
print(msg)
say("K2infocom!") # K2infocom! × 3
# ── retry(max_attempts, delay) ────────────────────────
def retry(max_attempts=3, delay=1, exceptions=(Exception,)):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for attempt in range(max_attempts):
try:
return func(*args, **kwargs)
except exceptions as e:
print(f"Attempt {attempt+1} failed: {e}")
if attempt + 1 < max_attempts:
time.sleep(delay)
raise RuntimeError(f"Failed after {max_attempts} attempts")
return wrapper
return decorator
@retry(max_attempts=3, delay=0.5, exceptions=(ConnectionError,))
def fetch_data(url):
# will retry up to 3 times on ConnectionError
return requests.get(url).json()
# ── require_role("admin") — access control ────────────
def require_role(*roles):
def decorator(func):
@functools.wraps(func)
def wrapper(user, *args, **kwargs):
if user.get("role") not in roles:
raise PermissionError(f"Role {roles} required")
return func(user, *args, **kwargs)
return wrapper
return decorator
@require_role("admin", "superuser")
def delete_user(user, user_id): ... # only admin/superuser can call
Stacking Multiple Decorators
Multiple decorators can be applied to the same function by stacking @ lines. They are applied bottom-up (innermost first) but
called top-down when the function is invoked.
Execution when called: timer → log_call → greet → log_call → timer
import functools, time
def timer(func):
@functools.wraps(func)
def wrapper(*a, **kw):
t = time.perf_counter()
r = func(*a, **kw)
print(f"⏱ {func.__name__}: {time.perf_counter()-t:.4f}s")
return r
return wrapper
def validate_positive(func):
@functools.wraps(func)
def wrapper(n, *a, **kw):
if n < 0:
raise ValueError(f"{func.__name__}: n must be >= 0")
return func(n, *a, **kw)
return wrapper
# ── Stack: @timer on top of @validate_positive ────────
@timer # 2nd applied: outer layer
@validate_positive # 1st applied: inner layer
def compute(n):
return sum(range(n))
compute(100000) # validates first, then times
# ⏱ compute: 0.0023s
# compute(-5) → ValueError: compute: n must be >= 0
# ── Equivalent longhand ───────────────────────────────
def compute(n): return sum(range(n))
compute = validate_positive(compute) # inner
compute = timer(compute) # outer
Real-World Decorator Patterns
Decorators are the backbone of most Python frameworks. Here are the most important production patterns used in Django, FastAPI, Flask, and professional Python services:
import functools, time
from collections import OrderedDict
# ── memoize — cache expensive results ────────────────
def memoize(func):
cache = {}
@functools.wraps(func)
def wrapper(*args):
if args not in cache:
cache[args] = func(*args)
return cache[args]
wrapper.cache = cache # expose for inspection
return wrapper
@memoize
def fib(n):
if n <= 1: return n
return fib(n-1) + fib(n-2)
print(fib(50)) # instant! (vs exponential without cache)
# Python built-in: functools.lru_cache(maxsize=128)
# ── class decorator — singleton pattern ──────────────
def singleton(cls):
"""Class decorator: ensures only one instance exists."""
instances = {}
@functools.wraps(cls)
def get_instance(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return get_instance
@singleton
class Config:
def __init__(self): self.debug = False
print(Config() is Config()) # True — same instance!
# ── Built-in Python decorators ────────────────────────
class Circle:
def __init__(self, radius): self.radius = radius
@property # makes area a readable attribute
def area(self):
import math; return math.pi * self.radius ** 2
@staticmethod # no self/cls — utility method
def validate(r): return r > 0
@classmethod # receives cls instead of self
def unit(cls): return cls(1)
c = Circle(5)
print(c.area) # 78.54 (no () needed — @property)
print(Circle.validate(5)) # True (@staticmethod)
print(Circle.unit().radius) # 1 (@classmethod)
Practice Python Online — Free Compilers
Don't want to install anything yet? Practice all decorator examples from this chapter directly in your browser with these free Python environments.
- Decorators are possible because Python functions are first-class objects — they can be stored, passed as arguments, and returned from other functions.
- A decorator is a function that takes a function, wraps it in a new function (the wrapper), and returns the
wrapper.
@decoratoris syntactic sugar forfunc = decorator(func). - Always apply
@functools.wraps(func)to the wrapper — it copies__name__,__doc__,__module__, etc., preventing identity loss. - Use
*args, **kwargsin the wrapper to handle any function signature — this makes the decorator universally applicable. - A decorator factory is a function that accepts configuration arguments and returns a decorator — adding an extra layer of nesting: factory → decorator → wrapper.
- When stacking decorators, they are applied bottom-up at definition time but executed top-down (outer first) when the function is called.
- Key real-world patterns:
@timer,@log_call,@memoize/@lru_cache,@retry,@require_role,@singleton. - Python's built-in decorators:
@property,@staticmethod,@classmethod,@functools.lru_cache,@dataclasses.dataclass.
The @decorator syntax is syntactic sugar — it's shorthand for
calling the decorator with the function and reassigning:
# This:
@my_decorator
def greet(): ...
# Is exactly the same as:
def greet(): ...
greet = my_decorator(greet)
The decorator receives the original function, wraps it in a new function with
added behaviour, and returns the wrapper. The name greet now
points to the wrapper.
Without @functools.wraps(func), the decorated function loses its
identity — __name__ becomes "wrapper", __doc__ becomes None, and introspection tools show the wrong information.
functools.wraps(func) copies the original
function's metadata (__name__, __qualname__, __doc__, __module__, __dict__, __annotations__) to the wrapper, and stores the original in wrapper.__wrapped__. This preserves debugging, logging, and
documentation behaviour.
A decorator factory is a function that accepts configuration arguments and returns a decorator. You need it when the decorator's behaviour should be configurable per use:
@repeat(3) # repeat(3) is called first → returns decorator
def say(): ...
Structure: factory(args) → decorator(func) → wrapper(*args, **kwargs). There are always three levels of nesting.
With stacked decorators:
@A # applied second (outer)
@B # applied first (inner)
def func(): ...
Application order (bottom-up): B is applied first → func = B(func), then A → func = A(func).
Execution order (top-down): when func() is called, A's wrapper runs first, then B's wrapper, then the
original function, then B returns, then A returns.
A decorator should be reusable across many different functions with different signatures. If the wrapper hardcoded specific parameters, it would only work for functions with exactly that signature.
Using *args, **kwargs makes the wrapper
transparently pass any arguments through to the original function — positional, keyword, or a
mix:
def wrapper(*args, **kwargs):
return func(*args, **kwargs) # forwards everything
This is why *args, **kwargs is the
standard pattern for all general-purpose decorator wrappers.
@my_decorator above a function definition
equivalent to?@repeat(3), how many
levels of nested functions does the implementation require?
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.