Python Tutorial 0/52 lessons ~6 min read Lesson 35

    Decorators

    A decorator is a function that takes a function and returns a new function.

    Course progress0%
    Focus
    8 guided sections
    Practice signal
    Examples included
    Career prep
    Foundation builder

    Introduction

    A decorator is a function that takes a function and returns a new function. Used for logging, timing, caching, auth, retries, route registration.

    Understanding the topic

    Core concepts to understand:

    • @deco = fn = deco(fn)
    • Use functools.wraps to preserve metadata.
    • Decorators with args = factory returning a decorator.
    • Class-based decorators with __call__.

    Syntax reference

    Visual flow / code:

    python
    from functools import wraps
    import time
    def timed(fn):
    @wraps(fn)
    def wrapper(*args, **kwargs):
    start = time.perf_counter()
    result = fn(*args, **kwargs)
    print(f"{fn.__name__}: {time.perf_counter()-start:.3f}s")
    return result
    return wrapper
    @timed
    def slow():
    time.sleep(0.5)
    # Parameterized decorator
    def retry(n: int):
    def deco(fn):
    @wraps(fn)
    def wrapper(*a, **kw):
    for i in range(n):
    try: return fn(*a, **kw)
    except Exception: pass
    raise
    return wrapper
    return deco

    Execution workflow

    1Decorators Workflow
    1 / 4

    Step 1

    @deco = fn = deco(fn)

    Apply this step while implementing decorators in real code.

    Real-world use

    FastAPI, Flask, Django, Celery, pytest — all use decorators as their public API. They're a Python superpower.

    Best practices

    • Always @wraps.
    • Keep decorator logic small.
    • Parameterized decorators = 3 nested fns.

    Hands-on exercise

    Interview preparation — practice these questions:

    • What's a decorator?
    • Why @wraps?
    • Walk through a parameterized decorator.

    Summary

    In summary: Functions transforming functions. Wraps preserves identity.

    Ready to mark this lesson complete?Track your journey across the entire course.