Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Iterators, generators & decoratorsMiddleVery commonTheory

What is a decorator, and what does `@my_decorator` above a function definition actually do?

Answer

A decorator is a callable that takes a target — most commonly a function or class — and returns a replacement for it, usually a wrapper that adds behavior around the original. A *decorator factory*, like `retry(times=3)`, is a related but distinct idea: it is a separate callable that itself returns the actual decorator, which is what lets `@retry(times=3)` work even though a decorator applied with `@` always conceptually takes just one target. Writing `@my_decorator` directly above `def func(): ...` is exactly equivalent to defining `func` normally and then immediately rebinding the name with `func = my_decorator(func)`; the decorator syntax is purely a readability shorthand for that rebinding, evaluated once when the enclosing `def` statement itself executes — at module import time for a top-level function, but at call time for a function defined inside another function, not necessarily "when the module is loaded."

Strong answer includes

  • decorator takes a target (function or class) and returns a replacement for it
  • a decorator factory is a separate callable that itself returns the real decorator, e.g. for @retry(times=3)
  • @decorator equals name = decorator(name), evaluated whenever that def statement executes — not always at module load

Practical example

Python example
@timed
def slow_task(): ...

is exactly the same as

Python example
def slow_task(): ...

followed by

Python example
slow_task = timed(slow_task)

; only one of these two spellings needs to be used, never both.

#decorators

Sources

The Python Language ReferencePython Software Foundation · Precise scoping, evaluation order and expression semanticsTop Python Interview Questions and AnswersInterviewBit · Coverage signal across syntax, decorators, generators and modules