Skip to main content
Python Beginner Practical Coding Topic: Functions & Closures

What are Python decorators and why use functools.wraps?

Quick Summary: A Python decorator is a callable that accepts a function or class and returns a wrapped version adding reusable behavior (auth checks, logging, caching, retries) without modifying original source code; @functools.wraps preserves metadata like __name__ and __doc__.

Written by Ravi Shankar Mishra (Founder & Lead Systems Architect, MockAttempt Academy) Reviewed by MockAttempt Engineering Editorial Desk
Last verified:

Direct Interview Answer

Because Python functions are first-class objects, @log_timing above def process_order(): is syntactic sugar for process_order = log_timing(process_order).

Decorating the inner wrapper with @functools.wraps(func) copies the wrapped function’s __name__, __doc__, annotations, and __wrapped__ attribute so FastAPI/OpenAPI introspection and debugging tracebacks remain intact.

Detailed Technical Explanation

When building decorators that take arguments (such as @retry(max_attempts=3)), you write a 3-level nested function: the outer factory captures arguments, the middle function receives func, and the inner wrapper executes on each call.

Practical Walkthrough

Reusable execution-timer decorator preserving function name and return value.

Code Example — PYTHON
import functools
import time

def timed(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = func(*args, **kwargs)
        elapsed_ms = (time.perf_counter() - start) * 1000
        print(f"{func.__name__} completed in {elapsed_ms:.2f}ms")
        return result
    return wrapper

@timed
def compute_sum(n: int) -> int:
    return sum(range(n))

print("Sum:", compute_sum(1000))
Expected Output / Verification
compute_sum completed in 0.03ms
Sum: 499500

Real-World Production Use Case

FastAPI authentication guards, rate-limiting decorators, Redis response caching, and retry backoff wrappers around flaky third-party webhooks.

Common Interview Mistakes to Avoid

  • Forgetting @functools.wraps(func), causing Flask/FastAPI route names and docs to break as wrapper().
  • Executing expensive setup inside wrapper() instead of outer decorator scope when initializing once.
Topics: #python #decorators #functools #closures
Learn. Practise. Prove. Get Career-Ready.

Ready to Build Your IT Career?

Explore industry-led programmes and develop practical skills through training, assessments and interview preparation.