Here’s a FastAPI endpoint and a Spring Boot endpoint:
@GetMapping("/health")
public String health() {
return "ok";
}@app.get("/health")
def health():
return "ok"They look like twins. They aren’t. This is the one place in Python where your Java instinct actively misleads you, so it’s worth getting right.
A Java annotation is metadata. It sits on the method and does nothing until a framework reads it later through reflection. A Python decorator is code: a function that runs immediately, at the moment Python reads the def, and can replace your function with a new one or register it somewhere.
This is part 10 of Python for Java Developers. Part 9 covered type hints, which many decorators read.
What the @ line really does
These two snippets are exactly the same:
@timer
def answer(question):
...
def answer(question):
...
answer = timer(answer)
That’s the whole mechanism. @timer above a function means: pass the function to timer, and bind the name to whatever timer returns. Functions are values in Python (part 5 showed this), so a decorator is just a function that takes a function.
A decorator you can read
Here’s a decorator that times every call:
import functools
import time
def timer(func):
@functools.wraps(func) # keep the name and docstring
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs) # call the original
print(f"{func.__name__} took {time.perf_counter() - start:.2f}s")
return result
return wrapper
@timer
def answer(question):
return call_model(question)
answer("What is RAG?") # prints "answer took 1.84s"
Step by step:
timerreceives the originalanswerfunction.- It defines a new function,
wrapper, which accepts any arguments (*args, **kwargs), calls the original, and adds timing around it. - It returns
wrapper, so the nameanswernow points towrapper. @functools.wraps(func)copies the original’s name and docstring ontowrapper, so logs and tools still seeanswer. Always use it when you write a decorator.
If you know Spring AOP, this is an @Around advice, written by hand in ten lines, with no proxy and no framework.
Two kinds of decorators
Every decorator you meet does one of two things. When you read one, ask: does it wrap my function, or register it?
- Wrapping decorators return a new function that adds behaviour around the original: timing, retries, caching, authentication checks.
timerabove is one. - Registering decorators record your function somewhere (a routing table, a list of tools) and usually return it unchanged. That’s how web frameworks and agent frameworks work.
A minimal registering decorator shows there’s no magic:
TOOLS = {}
def tool(func):
TOOLS[func.__name__] = func # register it
return func # return it unchanged
@tool
def get_weather(city: str) -> str:
"""Get the current weather for a city."""
...
TOOLS # {"get_weather": <function get_weather>}
Real agent frameworks do the same, plus they read the type hints and docstring to describe the tool to the model.
Decorators with arguments
@app.get("/health") has parentheses, so something extra happens. app.get("/health") is called first, and it returns the real decorator, which is then applied to your function:
@app.get("/health")
def health(): ...
# is the same as:
decorator = app.get("/health")
health = decorator(health)
Writing one takes three levels of functions: the outer one takes the arguments, the middle one takes the function, the inner one is the wrapper.
def retry(times):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for attempt in range(times):
try:
return func(*args, **kwargs)
except TimeoutError:
if attempt == times - 1:
raise
return wrapper
return decorator
@retry(times=3)
def fetch(url): ...
You’ll rarely write this yourself, but now you can read it.
Stacking decorators
Several decorators on one function apply from the bottom up: the one closest to the def wraps first.
@app.post("/summarize") # 2. register the timed function as an endpoint
@timer # 1. wrap summarize with timing
def summarize(req): ...
Decorators you’ll meet in real code
| Decorator | From | What it does | Kind |
|---|---|---|---|
@app.get(...), @app.post(...) |
FastAPI, Flask | Registers the function as an HTTP endpoint | registers |
@tool |
Agent frameworks | Turns a function into a tool the model can call | registers |
@pytest.fixture |
pytest | Registers test setup | registers |
@dataclass |
standard library | Generates __init__, __repr__, __eq__ for a class |
changes the class |
@property |
built in | Lets a method be read like a field | changes access |
@staticmethod, @classmethod |
built in | A method without self |
changes the method |
@functools.lru_cache |
standard library | Caches results per argument set | wraps |
@retry(...) |
tenacity | Retries the function on errors | wraps |
For example, retrying a flaky model call with the tenacity library:
from tenacity import retry, stop_after_attempt, wait_exponential
@retry(stop=stop_after_attempt(3), wait=wait_exponential(min=1, max=10))
def summarize(text):
return client.messages.create(...)
And caching expensive results, like embeddings for the same text:
from functools import lru_cache
@lru_cache(maxsize=1000)
def embed(text: str) -> tuple[float, ...]:
...
(lru_cache needs hashable arguments, and returning a tuple instead of a list keeps callers from changing the cached value.)
Annotations vs decorators, side by side
| Java annotation | Python decorator | |
|---|---|---|
| What it is | Metadata attached to code | A function that receives your function |
| When it acts | Later, when a framework reads it | Immediately, when the def runs |
| Changes the code? | Only through a framework (proxies, bytecode) | Yes, it can replace the function |
| Can you write one easily? | Annotation + processor or aspect | A plain function, ten lines |
Traps for Java developers
- Thinking it’s just metadata. A decorator runs code at import time, and it can change what calling your function does.
- Routes registered by import. Because registering decorators run when the module loads, an endpoint or tool exists only if its file is imported. “My route returns 404” often means the module is never imported.
- Forgetting
functools.wraps. Without it, every decorated function is namedwrapperin logs, tracebacks and tool schemas. - Decorator order. The bottom decorator applies first. Swapping two can change behaviour.
Key takeaways
@dabovedef fmeansf = d(f): a function call that runs right away.- A Java annotation is metadata; a Python decorator is code that wraps or registers your function.
- Ask of every decorator: does it wrap the function, or register it?
@name(args)callsname(args)first to get the real decorator.- Use
functools.wrapsin your own decorators, and remember they stack bottom up.
Frequently asked questions
Are Python decorators the same as Java annotations?
No. They share the @ symbol, but a Java annotation is passive metadata read later by a framework, while a Python decorator is a function that runs immediately and can replace or register the decorated function.
How does a Python decorator work?
@decorator above def f is shorthand for f = decorator(f). The decorator receives the function and returns something, usually a wrapper function or the original function after registering it.
What does functools.wraps do?
It copies the original function’s name, docstring and other metadata onto the wrapper. Without it, the decorated function looks like wrapper to logging, debugging and tools that inspect functions.
Can a decorator take arguments?
Yes. @retry(times=3) calls retry(times=3) first, which returns the actual decorator. That’s why decorators with arguments are written as a function inside a function inside a function.
What is the Python equivalent of Spring AOP?
For most uses, a decorator. Timing, logging, retries, caching and permission checks are written as decorators that wrap the function, without proxies or a container.
Next in the series: Python with and yield, the two keywords behind file handling and streaming LLM answers.
Comments