Python Decorators Demystified: Functions That Modify Functions
Decorators look like magic until you see what they actually do. Here is the plain-English version.
Decorators are one of Python's most elegant features — and one of the most confusing for beginners. Once you see the pattern, though, they become second nature.
What a Decorator Actually Is
A decorator is a function that takes a function, adds something to it, and returns the modified version. That is it. There is no magic.
Think of it as gift wrapping. The gift (your function) stays the same, but the wrapping (the decorator) adds something extra.
The Plain Version
def log_calls(func):
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__}")
return func(*args, **kwargs)
return wrapper
@log_calls
def add(a, b):
return a + b
add(2, 3) # Prints: Calling add
# Returns: 5
The @log_calls syntax is just shorthand for add = log_calls(add).
Real-World Uses
- Timing functions — measure how long a function takes
- Access control — check permissions before running a function
- Caching — store results to avoid recomputation
- Logging and debugging — trace function calls automatically
- Rate limiting — prevent functions from being called too often
Stacking Decorators
You can stack multiple decorators. They apply bottom-up:
@decorator_a
@decorator_b
def my_func():
pass
# Same as: my_func = decorator_a(decorator_b(my_func))
The Takeaway
Decorators are not magic — they are just functions that take functions. Once you see the wrapper pattern, you can build any decorator you need.
Happy coding!