- Courses
- 💻Programming Languages
- 🐍Python
- Intermediate Python & Best Practices
- Decorators
On this page
Decorators
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
Understanding Decorators
A decorator is a Python feature that allows you to wrap one function inside another to add behavior without modifying the original function’s code.
Decorators are essential for:
- Logging
- Authentication
- Caching
- Validation
- Performance measurement
- Reusable cross‑cutting logic
They are a cornerstone of clean, maintainable Python design.
The Core Idea Behind Decorators
A decorator is simply a function that:
- Accepts another function as input
- Returns a new function that adds behavior
- Preserves the original function’s interface
Example of a basic decorator:
def my_decorator(func):
def wrapper():
print("Before the function runs")
result = func()
print("After the function runs")
return result
return wrapper
Applying it:
@my_decorator
def greet():
print("Hello!")
Calling greet() now runs the wrapper around the original function.
Why Use the @ Syntax
The decorator syntax:
@decorator
def func():
...
is equivalent to:
func = decorator(func)
The @ form is clearer, more readable, and standard in professional Python codebases.
Decorators with Arguments
Most real‑world functions accept parameters, so decorators must handle them too.
def logger(func):
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__}")
return func(*args, **kwargs)
return wrapper
Usage:
@logger
def add(a, b):
return a + b
The wrapper uses *args and **kwargs to support any function signature.
Returning Values from Decorated Functions
Decorators must return the wrapped function’s result.
def double_result(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return result * 2
return wrapper
This pattern is essential for correctness.
Decorators That Accept Their Own Arguments
Sometimes the decorator itself needs configuration.
Example: a decorator that repeats a function call.
def repeat(times):
def decorator(func):
def wrapper(*args, **kwargs):
result = None
for _ in range(times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
Usage:
@repeat(3)
def say_hi():
print("Hi")
This pattern uses three layers:
- The outer function receives decorator arguments
- The middle function receives the function being decorated
- The inner function wraps the behavior
Preserving Metadata with functools.wraps
Decorators replace the original function with the wrapper, which can hide metadata like:
__name____doc__- Annotations
Use wraps to preserve them:
from functools import wraps
def logger(func):
@wraps(func)
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__}")
return func(*args, **kwargs)
return wrapper
This is a best practice in all production‑quality decorators.
Stacking Multiple Decorators
You can apply more than one decorator to a function.
@decorator_a
@decorator_b
def func():
...
Execution order:
decorator_bwraps the function firstdecorator_awraps the result
Decorators stack from bottom to top.
Real‑World Use Cases
Decorators appear everywhere in modern Python:
-
Logging
@logger def process(): ... -
Access control
@require_login def dashboard(): ... -
Caching
@lru_cache def compute(): ... -
Web frameworks
@app.route("/home") def home(): ... -
Testing
@pytest.mark.slow def test_big(): ...
Decorators provide clean, declarative syntax for cross‑cutting concerns.
Best Practices
- Always use
@wrapsto preserve metadata - Keep decorators small and focused
- Avoid modifying arguments unless intentional
- Document decorator behavior clearly
- Use decorator factories for configurable behavior
- Avoid overly clever decorator chains that reduce readability
Professional Python code uses decorators to improve clarity, not obscure logic.
Summary
Decorators allow you to wrap functions with additional behavior in a clean, reusable, and expressive way.
You learned how decorators work internally, how to handle arguments, how to preserve metadata, how to stack decorators, and how they appear in real‑world applications.
They are one of Python’s most powerful abstraction tools, enabling elegant and maintainable software design.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Generators
Next
Typing & Type Hints
- Understanding Decorators
- The Core Idea Behind Decorators
- Why Use the
@Syntax - Decorators with Arguments
- Returning Values from Decorated Functions
- Decorators That Accept Their Own Arguments
- Preserving Metadata with
functools.wraps - Stacking Multiple Decorators
- Real‑World Use Cases
- Best Practices
- Summary
