Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question

When multiple decorators are stacked above a single function, in what order do they apply?

Answer

Decorators apply bottom-up but execute outside-in. With `@a` then `@b` then `def f():`, Python first applies `b` to `f`, then applies `a` to the result of that, equivalent to `f = a(b(f))`. But at call time, execution goes the other way: calling the final decorated `f()` enters `a`'s wrapper first, which typically calls `b`'s wrapper, which then finally calls the original `f`. Mixing this up is a common source of bugs when decorator order actually matters, such as applying `@app.route(...)` above `@login_required` versus the reverse.

Strong answer includes

  • applied bottom-up: closest decorator wraps first
  • equivalent to f = a(b(f)) for stacked @a @b
  • execution at call time goes outside-in through the wrappers

Practical example

Python example
@log
@cache
def compute(): ...

applies `cache` first then `log` , so at call time `log` 's wrapper runs first and can time the entire cached call, including a cache miss falling through to `compute` .

#decorators#gotchas

Sources

The Python Language ReferencePython Software Foundation · Precise scoping, evaluation order and expression semantics