Tutorials Courses Interview Prep (100 Q&A) AI Tools (50) Developer Tools (50) Tracks Pricing Plans Blog & Articles Contact Us
Advanced Python Architecture & Async 18 mins read Free Lesson

Decorators, Closures & Metaprogramming in Python

Build function decorators with @functools.wraps, class decorators, and parameterised wrappers.

Authoring Custom Decorators

import time
import functools

def execution_timer(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = func(*args, **kwargs)
        elapsed = time.perf_counter() - start
        print(f"Function {func.__name__} took {elapsed:.4f}s")
        return result
    return wrapper

@execution_timer
def calculate_scores(n: int) -> int:
    return sum(i * i for i in range(n))