Decorators in Python 2026 – Best Practices for Writing Functions
Decorators are one of Python’s most powerful and elegant features. A decorator is a function that takes another function as input, adds some behavior to it, and returns a new function. In 2026, decorators are widely used for logging, authentication, caching, timing, validation, and more.
TL;DR — Key Takeaways 2026
- A decorator is a function that wraps another function to extend its behavior
- Use the
@decorator_namesyntax for clean application - Always use
functools.wrapsto preserve original function metadata - Decorators can accept parameters (decorator factories)
1. Basic Decorator
from functools import wraps
def timer(func):
"""Decorator that measures execution time."""
@wraps(func)
def wrapper(*args, **kwargs):
import time
start = time.perf_counter()
result = func(*args, **kwargs)
end = time.perf_counter()
print(f"{func.__name__} took {end - start:.4f} seconds")
return result
return wrapper
@timer
def slow_operation(n: int):
"""Simulate a slow task."""
import time
time.sleep(0.1)
return n * n
slow_operation(10)
2. Decorator with Parameters (Decorator Factory)
def repeat(times: int):
"""Decorator factory that repeats a function multiple times."""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
for _ in range(times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(3)
def greet(name: str):
print(f"Hello, {name}!")
greet("Alice")
3. Best Practices for Decorators in 2026
- Always use
@wraps(func)fromfunctoolsto preserve__name__,__doc__, and signature - Keep decorators simple and focused on a single responsibility
- Use decorator factories when you need to pass parameters
- Document what the decorator does and any side effects
- Consider using libraries like
wraptfor advanced decorator needs
Conclusion
Decorators are a cornerstone of modern Python development. In 2026, mastering decorators allows you to write clean, reusable, and powerful code by separating cross-cutting concerns from your core business logic. From simple timing and logging to complex authentication and caching, decorators remain one of Python’s most beloved features.
Next steps:
- Review your codebase and identify repeated behavior that can be replaced with decorators
- Related articles: Writing Functions in Python 2026 • Functions as Objects in Python 2026 • Defining a Function Inside Another Function in Python 2026