Programming & syntax · reviewed in August 2026
Decorator
A decorator is a Python function that wraps another function (or method) to add behavior — logging, timing, access control — without changing its internal code. It's applied with the @decorator_name syntax right above the function definition.
import time
def timed(func):
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
print(f"{func.__name__} took {time.perf_counter() - start:.4f}s")
return result
return wrapper
@timed
def process(data):
return sorted(data)Frequently asked questions
How does a decorator work internally?
It receives the original function as an argument and returns a new function (usually defined with *args and **kwargs) that runs logic before and/or after calling the original.
Can a decorator take its own arguments?
Yes, by adding an extra layer: a function that receives the decorator's arguments and returns the actual decorator, which in turn wraps the target function.
What are decorators used for in practice?
Registering routes in frameworks like FastAPI (@app.get(...)), caching results, timing execution, or requiring authentication before running a function — always cross-cutting logic that applies to many different functions.