Decorators: Wrapping Without Changing

Decorators: Wrapping Without Changing in Python: The Decorator pattern lets you add behaviour to a function or object without modifying its code.

Concept Explanation

The Decorator pattern lets you add behaviour to a function or object without modifying its code. Python has first-class syntax for it: @name.

@decorator
def do_thing():
    ...

# is exactly equivalent to
def do_thing():
    ...
do_thing = decorator(do_thing)

The @ is nothing but syntactic sugar for "pass this function to the decorator and bind the result to the same name."

Functions Are First-Class Objects

A function is a value. This is what makes decorators possible at all — you can pass a function as an argument, and a function can return a function.

def shout(text):
    return text.upper()

def whisper(text):
    return text.lower()

def call_twice(fn):
    def wrapper(*args, **kwargs):
        return fn(*args, **kwargs) + " " + fn(*args, **kwargs)
    return wrapper

call_twice(shout)("Hi")   # 'HI HI'

call_twice is a decorator, just without the @ sugar.

Closures: The Memoisation Device

A wrapper captures the original function in its closure — the variables are still reachable even after the enclosing function returns:

def make_counter():
    count = 0
    def increment(step=1):
        nonlocal count
        count += step
        return count
    return increment

c = make_counter()
c()      # 1
c()      # 2

nonlocal lets the inner function rebind a variable from the enclosing scope.

The Anatomy of a Well-Behaved Decorator

import functools

def timer(fn):
    @functools.wraps(fn)          # copies __name__, __doc__, __wrapped__, etc.
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = fn(*args, **kwargs)
        print(f"{fn.__name__} took {time.perf_counter() - start:.3f}s")
        return result
    return wrapper

functools.wraps matters. Without it, the wrapped function loses its __name__, __doc__, and signature — which breaks introspection, debugging, help(), and stack traces.

Parameterised Decorators

To pass arguments to a decorator, add one more level, so the decorator is a function that returns a decorator:

def retry(times=3, delay=0.1):
    def decorator(fn):
        @functools.wraps(fn)
        def wrapper(*args, **kwargs):
            for attempt in range(1, times + 1):
                try:
                    return fn(*args, **kwargs)
                except Exception:
                    if attempt == times:
                        raise
                    time.sleep(delay)
        return wrapper
    return decorator

@retry(times=5, delay=0.2)
def flaky_call():
    ...

Reading it right to left: @retry(times=5...) first evaluates retry(times=5, delay=0.2), which returns the inner decorator, which then receives flaky_call. Three nested functions because there are three responsibilities.

Class-Based Decorators

A class can be a decorator with __call__, which gives you per-call state:

class CountCalls:
    def __init__(self, fn):
        self.fn = fn
        self.calls = 0
    def __call__(self, *args, **kwargs):
        self.calls += 1
        return self.fn(*args, **kwargs)

Built-in Decorators You Already Use

@property, @staticmethod, @classmethod, @functools.lru_cache, @functools.cache, @dataclass, @contextmanager — these are all the same mechanism. @property turns a method into a computed attribute; @lru_cache does memoisation.


Code Example #1 (Basic)

The first decorators you'll actually write.

import functools
import time


def logger(fn):
    """Log every call with its arguments and return value."""
    @functools.wraps(fn)
    def wrapper(*args, **kwargs):
        args_repr = ", ".join(repr(a) for a in args)
        kwargs_repr = ", ".join(f"{k}={v!r}" for k, v in kwargs.items())
        call = ", ".join(filter(None, [args_repr, kwargs_repr]))
        print(f"-> {fn.__name__}({call})")
        result = fn(*args, **kwargs)
        print(f"<- {fn.__name__} returned {result!r}")
        return result
    return wrapper


@logger
def add(a, b):
    return a + b


@logger
def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"


add(3, 4)
greet("Ada")
greet("Ada", greeting="Howdy")


def timing(fn):
    @functools.wraps(fn)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = fn(*args, **kwargs)
        print(f"   [{fn.__name__}] {time.perf_counter() - start:.4f}s")
        return result
    return wrapper


# Decorators stack: the bottom one runs first (closest to the body).
@timing
@logger
def slow_add(a, b):
    time.sleep(0.05)
    return a + b


slow_add(1, 2)
print("\nStacking order: @timing wraps @logger wraps slow_add")
print("So call order is timing.wrapper -> logger.wrapper -> slow_add\n")


# Without functools.wraps, introspection breaks:
def bad_decorator(fn):
    def wrapper(*args, **kwargs):
        return fn(*args, **kwargs)
    return wrapper


@bad_decorator
def documented(doc):
    """This is a docstring."""
    return doc

print(f"with functools.wraps: {slow_add.__name__} / {slow_add.__doc__}")
print(f"without functools.wraps: name={documented.__name__!r} doc={documented.__doc__!r}")

The @property and @staticmethod built-ins are the same idea — the reason to learn decorators is not to write a logging one (though that is useful), it is that the language's own features are built on the mechanism.

Code Example #2 (Intermediate)

Parameterised decorators, class-based state, and a real policy decorator.

import functools
import time
import threading


# ---------- Parameterised: only allow calls during business hours ----------
def business_hours(start=9, end=18):
    """A decorator factory. The first call returns the actual decorator."""
    def decorator(fn):
        @functools.wraps(fn)
        def wrapper(*args, **kwargs):
            hour = time.localtime().tm_hour
            if not (start <= hour < end):
                raise RuntimeError(f"{fn.__name__} only runs during "
                                   f"{start:02d}:00-{end:02d}:00")
            return fn(*args, **kwargs)
        return wrapper
    return decorator


@business_hours(start=0, end=24)     # always allowed for the example
def generate_report(region):
    return f"report for {region}"


print(generate_report("emea"))


# ---------- Class-based: count calls per function ----------
class CountCalls:
    def __init__(self, fn):
        functools.update_wrapper(self, fn)
        self.fn = fn
        self.count = 0
    def __call__(self, *args, **kwargs):
        self.count += 1
        return self.fn(*args, **kwargs)


@CountCalls
def expensive_operation():
    return "done"


expensive_operation()
expensive_operation()
expensive_operation()
print(f"expensive_operation was called {expensive_operation.count} times\n")


# ---------- A useful policy: rate limiting ----------
class RateLimit:
    def __init__(self, max_calls, period=1.0):
        self.max_calls = max_calls
        self.period = period
        self._calls = []
        self._lock = threading.Lock()
    def __call__(self, fn):
        @functools.wraps(fn)
        def wrapper(*args, **kwargs):
            now = time.monotonic()
            with self._lock:
                self._calls = [t for t in self._calls if now - t < self.period]
                if len(self._calls) >= self.max_calls:
                    raise RuntimeError("rate limit exceeded")
                self._calls.append(now)
            return fn(*args, **kwargs)
        return wrapper


@RateLimit(max_calls=2, period=1.0)
def ping():
    return "pong"


for i in range(4):
    try:
        print(f"  call {i + 1}: {ping()}")
    except RuntimeError as exc:
        print(f"  call {i + 1}: {exc}")


# ---------- Decorators that accept arguments to the function itself ----------
def memoize(fn):
    """A hand-rolled lru_cache to show the mechanism."""
    cache = {}
    @functools.wraps(fn)
    def wrapper(n):
        if n not in cache:
            print(f"    computing fib({n})")
            cache[n] = fn(n)
        return cache[n]
    return wrapper


@memoize
def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)


print(f"\nfib(10) = {fib(10)} -- note how the memoization avoids repeats.")

The memoize example shows the danger of merely recognising a pattern: the simplest memoization cache works for immutable arguments but not for functions of many arguments, nor anything relying on lru_cache in a method. functools.cache and lru_cache handle the general case better.


Common Mistakes

  1. Forgetting @functools.wraps: the name and docstring vanish, which breaks help(), inspect, and stack tracebacks.
  2. Mutating the original function instead of returning a wrapper: if you set fn.name = ... in place and return fn, reusing the decorator on another function re-uses the altered state.
  3. Swapping wrapper order without thinking: decorators apply bottom-up. @timing + @logger is different from @logger + @timing.
  4. Using time.time() inside a decorator: use time.perf_counter for fine-grained durations.
  5. **Forgetting to forward *args, **kwargs: a wrapped function that takes keyword arguments will break.
  6. Returning something other than the result: a decorator that return None (instead of return result) silently discards the value.
  7. A parameterised decorator with the wrong number of nested functions: you need three layers when you take arguments.
  8. Thread-safety in a class-based decorator: if you keep mutable call state, guard it with a lock (see RateLimit).
  9. **Using ``` for docstrings while trying to use introspection**: a docstring meant for the wrapper can be lost if functools.wraps` is missing.
  10. Assuming @ is magic: it is plain assignment. If you can write the function call, you can write the decorator.

Best Practices

  • Always use @functools.wraps on your wrapper.
  • Keep the decorator as small as possible; if it needs lots of configuration, move the logic into a helper the wrapper calls.
  • Preserve *args, **kwargs so your decorator composes with any signature.
  • Use keyword-friendly parameterised decorators (a retry(times=3) instead of retry(3) unless you document it).
  • Set an attribute on the result when you want to mark it, e.g. wrapper._is_pure = True, so other code can detect it.
  • Guard state with a lock in concurrent code.
  • Prefer functools.lru_cache / functools.cache over a hand-rolled memoization for most cases.
  • Read decorators bottom-up when you are debugging a stack of them.
  • Use inspect.signature when you need the original signature rather than the wrapper's.
  • Name the parameterised decorator factory clearly (business_hours returns decorator), to make the three layers readable.
  • Log with the wrapper, not by reassigning the original.

Practice Exercises

  1. The Timing Wrapper: Write a @timer decorator that prints milliseconds and preserves __name__ and __doc__ using functools.wraps. Stack it with a @logger and check the order.
  2. The Retry Factory: Write @retry(times=4, delay=0.05) that re-runs a flaky function on exception, then re-raises after times attempts. Show that a function which succeeds on the third attempt eventually returns.
  3. The Rate Limiter: Implement a class-based @RateLimit(max_calls=2, period=1) and demonstrate that the third call within the window raises.