Decorators (@…)
A decorator is an @ line above a function or class that passes it through another function and keeps the result.
Used in 54 lessons of the course, from 00.07.
A decorator is written with @ right above a def or a class. It is a short way to write this:
greet = my_decorator(greet)
Python defines the function, hands it to the decorator, and stores whatever the decorator returns under the same name. Usually that is a new function that wraps the original: it adds something before or after, then calls it.
It is written this way so the extra behavior sits in plain sight, next to the name, and not hidden at the bottom of the code.
Some decorators take parentheses, like @dataclass(frozen=True) in the course. First dataclass(frozen=True) runs and returns the real decorator, and that decorator is applied to the class. This lets you pass options.
Reach for it when: you want to add behavior to a function or class without rewriting it, or when a library asks for it, as with `@dataclass`.
Examples
Common mistake
def anotar(func):
def envoltura():
print("llamando")
func()
return envoltura
@anotar
def doble():
return 2 * 5
print(doble())Why: The wrapper calls `func()` but doesn't return its result, so `doble()` returns `None`.
How to write it: Write return func() inside the wrapper.
Common mistake
def marcar(func):
print("marcada")
@marcar
def hola():
return 1
hola()Why: The decorator returns nothing, so `hola` becomes `None` and can't be called.
How to write it: Make the decorator return a function: return func or a wrapper.
