A decorator is a function that takes a function and returns a new one, usually a wrapper that does something before or after calling the original. It's how you add logging, timing, caching, checks or retries to many functions without changing their code. You've already used two: @cache and @dataclass.
Here's one written by hand. wrapper accepts any arguments (*args, **kwargs), passes them on to the original, and adds a line of output around it:
def announce(fn):
def wrapper(*args, **kwargs):
print(f"calling {fn.__name__}")
result = fn(*args, **kwargs)
print(f"{fn.__name__} returned {result}")
return result
return wrapper
def add(a, b):
return a + b
add = announce(add)
add(2, 3)
Prints
calling add
add returned 5
add = announce(add) replaces add with the wrapped version. The @ line is just shorthand for that: writing @announce above a def does exactly the same thing, at the moment the function is defined.
One problem: the wrapped function now reports itself as wrapper, losing its name and docstring, which confuses debuggers and documentation tools. functools.wraps copies them over. Put it on every wrapper you write.
A decorator that takes options, like @retry(times=3), needs one more layer: retry(times=3) is called first and must return the actual decorator. So it's a function that returns a decorator that returns a wrapper.
import functools
def retry(times):
def decorator(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
for attempt in range(1, times + 1):
try:
return fn(*args, **kwargs)
except ConnectionError:
print(f"attempt {attempt} failed")
raise ConnectionError(f"gave up after {times} tries")
return wrapper
return decorator
calls = {"n": 0}
@retry(times=3)
def flaky():
calls["n"] += 1
if calls["n"] < 3:
raise ConnectionError("no network")
return "ok"
print(flaky())
Prints
attempt 1 failed
attempt 2 failed
ok
Decorators stack: the one nearest the def is applied first. Frameworks lean on them heavily, for example @app.get("/items") in web frameworks registers a function as the handler for a web address. Classes can be decorated too, which is what @dataclass does. Built-in decorators you'll meet in classes are @property (a method read like an attribute, obj.area with no brackets), @staticmethod and @classmethod.