Skip to content

Python Decorators: Wrapping Functions to Add Behavior

  • What a decorator is and how the @ syntax works.
  • Writing a simple decorator that logs or times function calls.
  • Using functools.wraps to preserve the wrapped function’s metadata.
  • Writing decorators that accept their own arguments.

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:
@logger
def add(a, b):
return a + b
# Is exactly the same as:
def add(a, b):
return a + b
add = logger(add)

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
@logger
def add(a, b):
return a + b
@logger
def 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, Banky

The 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
@logger
def 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.' — preserved

Always use @functools.wraps(func) in every decorator you write.

A practical decorator that measures execution time:

from functools import wraps
import 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
@timed
def process_orders(count: int) -> list:
return [f"ORD-{i:04d}" for i in range(count)]
orders = process_orders(10000)
# process_orders took 2.3ms

Decorators that accept their own arguments need an extra layer of nesting — a decorator factory that returns the actual decorator:

from functools import wraps
import 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.

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... → 25
print(expensive_computation(5)) # 25 (from cache, no print)
print(expensive_computation.cache_info())
# CacheInfo(hits=1, misses=1, maxsize=128, currsize=1)
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_admin
def 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") # works
delete_order(regular, "ORD-002") # PermissionError
  • 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 wrapper does not return func(*args, **kwargs), the wrapped function’s return value is lost.