Skip to primary content
Python Technical Tutorial

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.

Python
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.

Key Engineering Takeaways
  • 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?
@decorator above def my_func() is exact syntactic sugar for my_func = decorator(my_func).
Master This in Our Ghaziabad Coding Labs

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
Physical Training Center

Visit Our Ghaziabad Training Center

Join classroom batches, attend interactive lab sessions, code with mentors, and take advantage of our high-speed dev workstations.

Campus Address:
C-60 R.K Tower, 3rd Floor, RDC, Ghaziabad, Ghaziabad, Uttar Pradesh
Direct Counseling Helpline:
Call 7503962162
Get Google Maps Directions Call Now: 7503962162 Explore Ghaziabad Training Hub
Call 7503962162 Get Course Details