ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

Python Tutorial• 7 min read

Decorators & *args / **kwargs

Higher-order wrapper functions, timing execution, and functools.wraps

Decorators are higher-order functions that wrap another function to extend or modify its behavior (e.g. logging, authentication, caching) without changing its source code.

Writing Reusable Decorators

*args collects positional arguments into a tuple; **kwargs collects keyword arguments into a dictionary.

Decorators take a target function as input and return a new wrapper function.

Always use @functools.wraps(func) on the wrapper to preserve the original function name and docstrings.

Execution Timer Decorator
import time
from functools import wraps

def time_execution(func):
    """Decorator measuring how long a function takes to execute."""
    @wraps(func)
    def wrapper(*args, **kwargs):
        start_time = time.perf_counter()
        result = func(*args, **kwargs)
        elapsed = time.perf_counter() - start_time
        print(f"Function '{func.__name__}' executed in {elapsed:.6f} seconds.")
        return result
    return wrapper

@time_execution
def compute_heavy_task(n):
    return sum(i * i for i in range(n))

print("Result:", compute_heavy_task(100_000))
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

What do `*args` and `**kwargs` allow a Python function to accept?