Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 10 / Topic 6 of 11

Decorators

A decorator is a function that takes a function and returns a new function that "wraps" it, adding extra behaviour before and/or after. Think of gift wrapping: the gift (your function) is unchanged, but there is now a layer around it.

A decorator by hand

def shout(func):
    def wrapper(name):
        result = func(name)
        return result.upper() + "!"
    return wrapper

def greet(name):
    return f"hello {name}"

greet = shout(greet)     # wrap it by hand
print(greet("asha"))     # HELLO ASHA!

The @ syntax

@shout above a def means exactly greet = shout(greet).

def shout(func):
    def wrapper(name):
        return func(name).upper() + "!"
    return wrapper

@shout
def greet(name):
    return f"hello {name}"

print(greet("ravi"))     # HELLO RAVI!

functools.wraps and any arguments

A real decorator should work for any function, so the wrapper takes *args, **kwargs and passes them on. Add @wraps(func) so the wrapped function keeps its own name and docstring.

Real-world example: a logger.

from functools import wraps

def logger(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        print(f"calling {func.__name__} with {args} {kwargs}")
        result = func(*args, **kwargs)
        print(f"{func.__name__} returned {result}")
        return result
    return wrapper

@logger
def add_gst(amount, rate=18):
    """Add GST to an amount."""
    return amount + amount * rate // 100

add_gst(1000, rate=12)
print(add_gst.__name__, "|", add_gst.__doc__)

Output:

calling add_gst with (1000,) {'rate': 12}
add_gst returned 1120
add_gst | Add GST to an amount.

Without @wraps, the last line would say wrapper | None.

Real-world example: a timer.

import time
from functools import wraps

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

@timer
def make_report():
    time.sleep(0.5)          # pretend this is slow work
    return "done"

print(make_report())

Output (time varies a little):

make_report took 0.5s
done

Decorators with arguments

To write @retry(times=3), you need one more layer: a function that takes the settings and returns a decorator.

from functools import wraps

def retry(times):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            for attempt in range(1, times + 1):
                try:
                    return func(*args, **kwargs)
                except ConnectionError:
                    print(f"attempt {attempt} failed")
            raise ConnectionError(f"gave up after {times} tries")
        return wrapper
    return decorator

tries = []

@retry(times=3)
def send_sms():
    tries.append(1)
    if len(tries) < 3:              # fail twice, then work
        raise ConnectionError("network down")
    return "SMS sent"

print(send_sms())

Output:

attempt 1 failed
attempt 2 failed
SMS sent
Layer Receives Returns
retry(times) the settings decorator
decorator(func) the function wrapper
wrapper(*args, **kwargs) the call's arguments the result

Built-in decorator: functools.lru_cache / cache

Caching means remembering answers so the same question is not worked out twice. @lru_cache(maxsize=128) remembers the last 128 answers; @cache (same as maxsize=None) remembers all of them.

from functools import cache

@cache
def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)

print(fib(80))           # 23416728348467685  (instant; without @cache it takes ages)
print(fib.cache_info())  # CacheInfo(hits=78, misses=81, maxsize=None, currsize=81)

Only cache pure functions: same input always gives the same output, with no side effects.

๐Ÿ” Going deeper: you can stack decorators; the one nearest the def is applied first. Arguments to a cached function must be hashable (no lists or dicts).

Full program: examples/03_closures_and_decorators.py.

Done here? The practice set for Part 10 โ€” 8 exercises with solutions โ€” is on the part page.

Search the guide