Python Decorators: Wrapping Functions to Add Behavior
What you’ll learn
Section titled “What you’ll learn”- What a decorator is and how the
@syntax works. - Writing a simple decorator that logs or times function calls.
- Using
functools.wrapsto preserve the wrapped function’s metadata. - Writing decorators that accept their own arguments.
Prerequisites
Section titled “Prerequisites”- Python 3.9+ installed
- Familiarity with functions (functions tutorial)
What is a decorator?
Section titled “What is a decorator?”A decorator is a function that wraps another function to add behavior — logging, timing, access control, caching — without modifying the wrapped function’s code. The @decorator_name syntax above a function definition is shorthand for func = decorator_name(func).
# This:@loggerdef add(a, b): return a + b
# Is exactly the same as:def add(a, b): return a + badd = logger(add)Step 1 — A simple logging decorator
Section titled “Step 1 — A simple logging decorator”Save as decorators.py and run with python decorators.py (Python 3.9+):
def logger(func): """Decorator that prints calls to the wrapped function.""" def wrapper(*args, **kwargs): print(f"Calling {func.__name__}({args}, {kwargs})") result = func(*args, **kwargs) print(f"{func.__name__} returned {result}") return result return wrapper
@loggerdef add(a, b): return a + b
@loggerdef greet(name): return f"Hello, {name}"
print(add(2, 3))# Calling add((2, 3), {})# add returned 5# 5
print(greet("Banky"))# Calling greet(('Banky',), {})# greet returned Hello, Banky# Hello, BankyThe wrapper function uses *args, **kwargs so it works with any function signature. The decorator returns wrapper, which replaces the original function.
Step 2 — Preserving metadata with functools.wraps
Section titled “Step 2 — Preserving metadata with functools.wraps”Without @functools.wraps, the wrapped function loses its __name__, __doc__, and other metadata. This breaks introspection, debugging, and documentation tools.
from functools import wraps
def logger(func): @wraps(func) # copies func's metadata onto wrapper def wrapper(*args, **kwargs): print(f"Calling {func.__name__}") return func(*args, **kwargs) return wrapper
@loggerdef add(a, b): """Add two numbers.""" return a + b
print(add.__name__) # 'add' — correct (would be 'wrapper' without @wraps)print(add.__doc__) # 'Add two numbers.' — preservedAlways use @functools.wraps(func) in every decorator you write.
Step 3 — A timing decorator
Section titled “Step 3 — A timing decorator”A practical decorator that measures execution time:
from functools import wrapsimport time
def timed(func): @wraps(func) def wrapper(*args, **kwargs): start = time.perf_counter() result = func(*args, **kwargs) elapsed = (time.perf_counter() - start) * 1000 print(f"{func.__name__} took {elapsed:.1f}ms") return result return wrapper
@timeddef process_orders(count: int) -> list: return [f"ORD-{i:04d}" for i in range(count)]
orders = process_orders(10000)# process_orders took 2.3msStep 4 — Decorators with arguments
Section titled “Step 4 — Decorators with arguments”Decorators that accept their own arguments need an extra layer of nesting — a decorator factory that returns the actual decorator:
from functools import wrapsimport time
def retry(max_attempts: int = 3, delay: float = 1.0): """Decorator factory: retry on exception up to max_attempts times.""" def decorator(func): @wraps(func) def wrapper(*args, **kwargs): for attempt in range(1, max_attempts + 1): try: return func(*args, **kwargs) except Exception as e: if attempt == max_attempts: raise print(f"Attempt {attempt} failed: {e}. Retrying in {delay}s...") time.sleep(delay) return wrapper return decorator
@retry(max_attempts=3, delay=0.5)def fetch_order(order_id: str) -> dict: # Simulate a flaky API call import random if random.random() < 0.5: raise ConnectionError("API unavailable") return {"id": order_id, "status": "shipped"}
try: order = fetch_order("ORD-001") print(order)except ConnectionError: print("All retries exhausted")The structure is: retry(max_attempts=3) returns decorator, which is applied to fetch_order via the @ syntax.
Step 5 — Practical patterns
Section titled “Step 5 — Practical patterns”Caching with lru_cache
Section titled “Caching with lru_cache”The standard library provides functools.lru_cache as a ready-made memoization decorator:
from functools import lru_cache
@lru_cache(maxsize=128)def expensive_computation(n: int) -> int: print(f"Computing for {n}...") return n * n
print(expensive_computation(5)) # Computing for 5... → 25print(expensive_computation(5)) # 25 (from cache, no print)print(expensive_computation.cache_info())# CacheInfo(hits=1, misses=1, maxsize=128, currsize=1)Access control
Section titled “Access control”from functools import wraps
def require_admin(func): @wraps(func) def wrapper(user: dict, *args, **kwargs): if not user.get("is_admin"): raise PermissionError(f"User {user.get('name')} is not an admin") return func(user, *args, **kwargs) return wrapper
@require_admindef delete_order(user: dict, order_id: str) -> None: print(f"Order {order_id} deleted by {user['name']}")
admin = {"name": "Alice", "is_admin": True}regular = {"name": "Bob", "is_admin": False}
delete_order(admin, "ORD-001") # worksdelete_order(regular, "ORD-002") # PermissionErrorCommon mistakes
Section titled “Common mistakes”- Forgetting
@wraps(func). The wrapped function silently loses__name__,__doc__, and signature, which breaks introspection, help text, and some testing/debugging tools. - Wrong nesting for parameterized decorators. A decorator with arguments needs three layers: factory → decorator → wrapper. Forgetting one layer causes a
TypeError. - Not returning the result. If
wrapperdoes notreturn func(*args, **kwargs), the wrapped function’s return value is lost.
Next steps
Section titled “Next steps”- Functions tutorial — closures, which decorators build on
- lru_cache feature guide — memoization in depth
- OOP tutorial — class-based decorators
Official references
Section titled “Official references”- Python docs: functools —
wraps,lru_cache - PEP 318 — decorators syntax