Mastering Python Decorators: Closures, Function Wrappers & Timing Metrics
Complete tutorial on writing custom Python decorators: first-class functions, inner wrappers, functools.wraps, and execution timing benchmarks.
import time
from functools import wraps
def execution_timer(func):
"""Measures execution duration of the decorated function."""
@wraps(func)
def wrapper(*args, **kwargs):
start_time = time.perf_counter()
result = func(*args, **kwargs)
duration = time.perf_counter() - start_time
print(f"[{func.__name__}] completed in {duration:.6f} seconds")
return result
return wrapper
@execution_timer
def process_large_dataset(n: int):
return sum(i * i for i in range(n))
process_large_dataset(1_000_000)
1. Functions as First-Class Citizens
In Python, functions can be assigned to variables, passed as arguments, and returned from other functions. A decorator is simply a function that accepts another function as an argument, adds behavior, and returns the modified function.
2. Preserving Function Metadata with functools.wraps
When wrapping a function, its original __name__ and docstring are obscured by the wrapper function. Applying @wraps(func) preserves the original function's introspection metadata, which is crucial for debugging and testing frameworks.
- Decorators provide clean, reusable aspect-oriented functionality such as logging, authentication, and caching.
- Always use @wraps from the functools module inside your custom decorators.
- Decorators can also take configuration arguments by adding an extra outer wrapper layer.
Frequently Asked Questions
What is the @ syntax shorthand for?
Gain deep mastery over these concepts with direct instructor guidance, code reviews, and mock interviews at C-60 R.K Tower, 3rd Floor, RDC, Ghaziabad.
Explore Related Course Call 7503962162