Python decorators explained in plain terms: a decorator is a function that takes another function, adds behavior around it, and hands back a new function that does the extra work plus the original job. You have probably used them already. Flask routes, pytest markers, and property setters all rely on decorators, even if you never wrote one yourself. Once you see the pattern, you will spot places in your own code where a decorator removes repetition instead of adding magic.
Decorators look strange at first because the syntax hides a simple idea. The @ sign above a function is shorthand for passing that function through another function and rebinding the name. Nothing else happens. There is no special runtime, no framework hook, just functions returning functions. That is the whole trick, and everything in this guide builds on it.
What a Decorator Actually Does
A function in Python is an object. You can pass it as an argument, store it in a variable, and return it from another function. A decorator uses all three. It accepts a function, defines a wrapper function inside itself, and returns the wrapper. When you call the decorated function, you are really calling the wrapper, which runs its extra code and then calls the original.
Here is the smallest useful example. It prints a message before and after the wrapped function runs:
def announce(func):
def wrapper(*args, **kwargs):
print("Starting...")
result = func(*args, **kwargs)
print("Done.")
return result
return wrapper
@announce
def greet(name):
print(f"Hello, {name}")
greet("Maya")
Calling greet("Maya") prints Starting, then Hello Maya, then Done. The line @announce is the same as writing greet = announce(greet) after the definition. The *args and **kwargs in the wrapper matter: they let the decorator work with any function, whatever arguments it takes. Leave them out and the decorator breaks the moment a function takes a parameter.
If you want the mental model behind functions passed as values, the guide on JavaScript closures explained with real code examples covers the same idea in another language, and the closure concept transfers directly to how wrappers remember the function they wrap.
Python Decorators Explained with a First Real Example
The announce example is clear but not useful. A better first decorator is a timer. You want to know how long a slow function takes, but you do not want timing code pasted into every function you measure. A decorator keeps the timing in one place:
import time
from functools import wraps
def timed(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
print(f"{func.__name__} took {time.time() - start:.2f}s")
return result
return wrapper
@timed
def fetch_users():
time.sleep(1)
return ["ana", "ben"]
Two details deserve attention. First, @wraps(func) copies the original name and docstring onto the wrapper. Without it, every decorated function reports its name as wrapper, which makes tracebacks confusing and breaks tools that read function metadata. Always use it. Second, the wrapper returns the result of the original function. Forgetting that return is the most common decorator bug: the function runs, but the caller gets None.
Decorators also help when a script grows past a few files. A Python project that starts as one file soon needs structure, and the walkthrough on building a RAG pipeline in Python shows how small reusable pieces, decorators included, keep a larger codebase readable.
Decorators That Take Arguments
Sometimes the decorator itself needs settings. A retry decorator, for example, should let you choose how many times to retry. That needs one more layer: a function that takes the settings and returns the decorator.
def retry(times=3):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
for attempt in range(times):
try:
return func(*args, **kwargs)
except Exception:
if attempt == times - 1:
raise
return wrapper
return decorator
@retry(times=2)
def call_api():
return "ok"
Read it from the outside in. retry(times=2) runs first and returns the decorator. That decorator receives call_api and returns the wrapper. The wrapper runs the function, catches failures, and tries again. Three layers look heavy, but each layer has one job, and that separation is what makes the pattern easy to test: you can call the inner function directly, or test the wrapper with a function that always fails.
A decorator with arguments is also where beginners get confused about order. The arguments belong to the outer call, not to the wrapped function. If you write @retry without parentheses on a decorator built this way, Python passes the function itself as the first argument and everything breaks in a strange way. Match the call style to the definition: no parentheses means the decorator takes the function directly, parentheses mean it takes settings first.
Real Uses: Logging, Timing, and Caching
Three uses cover most of what decorators do in real projects. Logging wraps a function to record its inputs and outputs without touching its body. Timing measures slow paths, as above. Caching stores results so repeated calls with the same arguments skip the work entirely. Python ships a cache decorator in the standard library, and it takes one line:
from functools import lru_cache
@lru_cache(maxsize=128)
def slow_lookup(key):
return key.upper()
Call slow_lookup("abc") twice and the second call returns the stored result. The cache only works when arguments are hashable, so lists and dicts as arguments will raise an error. That limit is worth knowing before you sprinkle caching everywhere.
Another common use is access control in web code. A decorator can check whether a user is logged in before a view runs, and redirect when they are not. The view stays focused on its own job, and the check lives in one place. The same idea applies to validation, rate limiting, and feature flags: anything that wraps many functions with the same rule is a candidate.
Common Mistakes to Avoid
The first mistake is stacking decorators without thinking about order. Decorators apply bottom to top, so the one closest to the function runs first. A logging decorator above a timing decorator measures a different thing than the reverse order. When a stack misbehaves, read it from the bottom up.
The second mistake is decorating a function that other code calls by its original behavior. A decorator changes what the name points to. If a test patches the original function, or another module imported the function before decoration, the decorated version may never run. Keep decorators on functions you own, and keep the wrapper behavior close to the original: same arguments, same return value, same exceptions.
The third mistake is hiding errors. A wrapper that catches every exception and returns None turns a loud failure into a silent wrong answer. Let exceptions pass through unless the decorator exists to handle them, like retry. When a decorated function fails in a confusing way, check the wrapper first: a missing return, a swallowed exception, or a dropped argument is usually the cause. If the traceback points at the wrapper instead of your code, the guide on how to read a stack trace and find the real bug shows how to follow the frames back to the real line.
When Not to Use a Decorator
A decorator is the wrong tool when the behavior belongs to one function only. Wrapping a single function to add one print statement adds a layer of indirection for no reuse. It is also the wrong tool when the wrapped behavior needs to change at runtime in ways the wrapper cannot see, or when the function signature matters to a framework that inspects it. In those cases, write the code plainly inside the function.
Use a decorator when the same wrapper fits three or more functions, or when it separates a cross-cutting concern like logging, auth, or caching from the work itself. Start with the plain version, notice the repetition, then extract it. Decorators reward that order: write the repeated code first, then factor it out, and the wrapper you end up with does exactly what your code already needed.