Skip to main content
A stacked decorator in Python refers to the application of multiple decorators to a single function or method. This technique leverages function composition, where the output (the returned wrapper function) of one decorator becomes the input to the next, creating a nested chain of higher-order functions.

Syntax

Decorators are stacked by placing multiple @decorator_name statements on consecutive lines directly above the target function definition.

Underlying Mechanics

When the Python interpreter evaluates a stacked decorator, it translates the syntactic sugar into standard function calls. The evaluation strictly follows mathematical function composition: f(g(h(x)))f(g(h(x))). The syntax block above is functionally identical to the following reassignment:

Application vs. Execution Order

Understanding stacked decorators requires distinguishing between application order (when the function is wrapped) and execution order (when the wrapped function is called).
  1. Application Order (Bottom-Up): Decorators are applied from the innermost to the outermost. The decorator closest to the function definition (@decorator_gamma) receives the original function first. Its returned wrapper is then passed to @decorator_beta, and so on.
  2. Execution Order (Top-Down, then Bottom-Up): When the decorated function is invoked, the execution flows through the wrappers from the outermost to the innermost. Code preceding the func() call executes top-down. Code following the func() call executes bottom-up as the call stack unwinds.

Execution Flow Demonstration

The following code illustrates the call stack behavior of stacked decorators:
Standard Output:

Metadata Preservation

Because stacked decorators create multiple layers of wrapper functions, the original function’s introspection metadata (__name__, __doc__, __annotations__) is easily masked by the outermost wrapper. To maintain accurate metadata through the entire stack, every decorator in the chain must utilize functools.wraps. If even one decorator in the stack omits it, the metadata chain is broken.
Tired of Poor Python Skills? Fix That With Deep Grasping!Learn More