Decorators
A decorator is a higher-order function that takes a function as input, adds some behaviour, and returns a new function. The @ syntax is syntactic sugar for...
What is a Decorator?
A decorator is a higher-order function that takes a function as input, adds some behaviour, and returns a new function. The @ syntax is syntactic sugar for applying decorators. @my_decorator above def f() is exactly equivalent to f = my_decorator(f). Decorators are used to add cross-cutting concerns like logging, authentication, caching, timing, and input validation without modifying the original function's code. The separation of concerns they provide is a key benefit.
Writing a Simple Decorator
def logger(func): def wrapper(*args, **kwargs): print(f"Calling {func.__name__}"); result = func(*args, **kwargs); print(f"Done"); return result; return wrapper. Apply it: @logger; def add(a, b): return a + b. Calling add(2, 3) now prints "Calling add", returns 5, and prints "Done". The wrapper uses *args, **kwargs to accept any arguments and passes them through to the original function, making the decorator work with any function signature.
Preserving Metadata with functools.wraps
When you wrap a function with a decorator, the wrapper function replaces the original. This means the __name__ and __doc__ attributes become those of wrapper, not the original function. Fix this with @functools.wraps(func) on the wrapper: from functools import wraps; def logger(func): @wraps(func); def wrapper(*args, **kwargs): ...; return wrapper. Now the wrapped function's __name__ and __doc__ are correctly preserved, which matters for debugging, documentation, and introspection tools.
Decorators with Arguments
To create a decorator that itself takes arguments, add an outer factory function. def repeat(n): def decorator(func): def wrapper(*args, **kwargs): for _ in range(n): func(*args, **kwargs); return wrapper; return decorator. Apply: @repeat(3); def hello(): print("Hi"). Calling hello() prints "Hi" three times. This three-level nesting (factory → decorator → wrapper) is the standard pattern for parameterised decorators and is commonly used in web frameworks for route configuration.
Stacking Multiple Decorators
You can apply multiple decorators to a single function by stacking @decorator lines. They are applied bottom-up: @a; @b; def f() is equivalent to f = a(b(f)). Order matters — the bottommost decorator is applied first, and its result is passed to the one above it. Common real-world stacking: applying @login_required and @cache together on a Django view function. Always reason about the order of application when debugging unexpected decorator interactions.
Exam Tip
Decorators are a popular advanced Python interview topic. Key questions: what does @wraps do and why is it needed? It copies metadata (__name__, __doc__) from the original function to the wrapper. What is the execution order when decorators are stacked? Bottom-up at decoration time, then the outermost wrapper runs first at call time. Can a decorator be used on a class method? Yes, using @staticmethod, @classmethod, and @property are all built-in decorators that work on methods. Be able to write a decorator from scratch without looking it up.