LearnFrenzy
Sign in Take a free test

Advanced Python · Lesson 35 of 39

Decorators and Context Managers

5 min read Updated Nov 7, 2026 Saurabh Samir

You have already used decorators – @property, @dataclass, @lru_cache – and context managers – with open(...). Both are ways to wrap extra behaviour around your code without changing the code itself. Web frameworks use decorators for routes (@app.get("/")), and testing tools use them everywhere. Here is how they work and how to write your own.

In this lesson

  • The building blocks: functions as values and closures
  • Writing a decorator and using the @ syntax
  • functools.wraps and decorators with arguments
  • Context managers with @contextmanager

Building block: a function that returns a function

def make_multiplier(factor):
    def multiply(n):
        return n * factor      # remembers factor: a closure
    return multiply

double = make_multiplier(2)
triple = make_multiplier(3)
print(double(10), triple(10))

Output

20 30

A decorator uses exactly this idea: it takes a function and returns a new function that wraps it.

Your first decorator

def announce(func):
    def wrapper(*args, **kwargs):
        print(f"→ calling {func.__name__}{args}")
        result = func(*args, **kwargs)
        print(f"← {func.__name__} returned {result}")
        return result
    return wrapper

@announce
def add(a, b):
    return a + b

add(2, 3)

Output

→ calling add(2, 3)
← add returned 5

@announce above the def is just a short way of writing add = announce(add). From then on, the name add refers to wrapper, which calls the original add in the middle.

Calling a decorated function

  1. add(2, 3)actually calls wrapper(2, 3)
  2. Beforewrapper runs its extra code
  3. func(*args, **kwargs)the original add runs
  4. Afterwrapper runs more code and returns the result

*args, **kwargs let the wrapper accept any arguments and pass them through unchanged, so one decorator works on any function.

A practical decorator: timing

import time
from functools import wraps

def timed(func):
    @wraps(func)                         # keep the original name and docstring
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = func(*args, **kwargs)
        elapsed = time.perf_counter() - start
        print(f"{func.__name__} took {elapsed:.1f}s")
        return result
    return wrapper

@timed
def build_report():
    """Pretend to do slow work."""
    time.sleep(0.2)
    return "report ready"

print(build_report())
print(build_report.__name__, "|", build_report.__doc__)

Output

build_report took 0.2s
report ready
build_report | Pretend to do slow work.

Common mistake: forgetting @wraps

Without @functools.wraps(func), the decorated function's name becomes wrapper and its docstring disappears, which confuses debuggers, documentation tools and frameworks. Always add it.

Decorators with arguments

To pass settings, add one more layer: a function that takes the settings and returns the actual 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 as error:
                    print(f"attempt {attempt} failed: {error}")
            raise ConnectionError(f"gave up after {times} attempts")
        return wrapper
    return decorator

calls = {"n": 0}

@retry(times=3)
def fetch_rates():
    calls["n"] += 1
    if calls["n"] < 3:
        raise ConnectionError("timeout")
    return {"USD": 84.2}

print(fetch_rates())

Output

attempt 1 failed: timeout
attempt 2 failed: timeout
{'USD': 84.2}

Where you'll see decorators

DecoratorWhat it adds
@property, @classmethod, @staticmethodspecial method types in classes
@dataclassgenerated __init__, __repr__, __eq__
@functools.lru_cacheremembers results (memoisation)
@app.get("/users") (FastAPI, Flask)registers a function as a web route
@pytest.mark.parametrizeruns a test with many inputs

Context managers: with

A context manager runs set-up code when a with block starts and clean-up code when it ends – even if an error occurs. open() is one; you can write your own easily with @contextmanager. Code before yield is the set-up, code after it is the clean-up:

from contextlib import contextmanager
import time

@contextmanager
def stopwatch(label):
    start = time.perf_counter()
    try:
        yield
    finally:
        print(f"{label}: {time.perf_counter() - start:.1f}s")

with stopwatch("loading data"):
    time.sleep(0.3)
print("after the block")

Output

loading data: 0.3s
after the block

A context manager can also hand a value to the as name and guarantee clean-up when things fail:

from contextlib import contextmanager

@contextmanager
def transaction(db):
    print("BEGIN")
    try:
        yield db
        print("COMMIT")
    except Exception:
        print("ROLLBACK")
        raise

accounts = {"asha": 500}
try:
    with transaction(accounts) as db:
        db["asha"] -= 800
        if db["asha"] < 0:
            raise ValueError("overdrawn")
except ValueError as error:
    print("error:", error)

Output

BEGIN
ROLLBACK
error: overdrawn

(A real database library would also undo the change on rollback; here we only print the steps.)

Practice

Try it yourself

  1. Write a decorator @uppercase that converts a function's string result to upper case.

    Show solution
    from functools import wraps
    
    def uppercase(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            return func(*args, **kwargs).upper()
        return wrapper
    
    @uppercase
    def greet(name):
        return f"hello, {name}"
    
    print(greet("tara"))

    Output

    HELLO, TARA
  2. Write a decorator that counts how many times a function has been called and stores it in wrapper.calls.

    Show solution
    from functools import wraps
    
    def count_calls(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            wrapper.calls += 1
            return func(*args, **kwargs)
        wrapper.calls = 0
        return wrapper
    
    @count_calls
    def ping():
        return "pong"
    
    ping(); ping(); ping()
    print(ping.calls)

    Output

    3

Quick check

What is @deco above def f equivalent to?

f = deco(f)

Why use *args, **kwargs in a wrapper?

So the wrapper accepts and forwards any arguments, making the decorator work with any function.

In a @contextmanager function, when does the code after yield run?

When the with block ends (put it in finally so it also runs after an error).

Summary

  • A decorator takes a function and returns a wrapper; @deco means f = deco(f).
  • Use *args, **kwargs and @functools.wraps in every wrapper.
  • Add an outer function for decorators with arguments.
  • Context managers wrap set-up and clean-up around a with block.

Finished this lesson?

Mark it complete to track your progress, then carry on with the next lesson.

Next lesson

Search LearnFrenzy

Esc

Quick links