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
@timed
def slow_task(): ...is exactly the same as
def slow_task(): ...followed by
slow_task = timed(slow_task); only one of these two spellings needs to be used, never both.