Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

PY
Python
0/14 completed
Beginner
Hello PythonVariables and typesWorking with stringsConditions and loopsFunctions
Intermediate
Lists, tuples, dicts and setsFiles and exceptionsModules and the standard library
Advanced
Classes and OOPIterators and generatorsDecorators and context managers
Pro
Async PythonTesting and type hintsVirtual environments, packages and real projects
Tracks / Python / Advanced

Decorators and context managers

Two features that make Python code elegant: decorators wrap functions with extra behaviour (timing, logging, caching, permission checks), and context managers guarantee that setup and cleanup always happen together (with open(...)). Frameworks like Flask, FastAPI and pytest use both everywhere.

Functions are objects

A decorator relies on two facts: functions can be passed around like any value, and you can define a function inside another function:

Python · editable

Your first decorator

A decorator is a function that takes a function and returns a new, improved one:

Python · editable

*args, **kwargs lets the wrapper accept any arguments and pass them through unchanged.

Useful real decorators

Timing

Python · editable

Always use @wraps(func), or every decorated function will be called "wrapper" in tracebacks and tools.

Caching

The standard library ships a caching decorator. Watch it turn an exponentially slow function into an instant one:

Python · editable

@lru_cache(maxsize=1000) is the variant with a size limit.

Decorators with arguments

Add one more layer of function to accept arguments:

Python · editable

Decorators in frameworks

You'll recognise this shape everywhere:

python
@app.get("/users/{user_id}")        # FastAPI: register a route
async def get_user(user_id: int): ...

@pytest.fixture                     # pytest: provide test data
def db(): ...

@login_required                     # Django: permission check
def dashboard(request): ...

Context managers

A context manager runs setup code when a with block starts and cleanup code when it ends, even if an error happens:

Python · editable

Writing one with contextlib

Python · editable

A class-based context manager

Python · editable

__exit__ receives the exception (if any). Returning True swallows it; returning None/False lets it continue.

Handy built-in context managers

Python · editable

Practice

  1. Write a @log_calls decorator that prints the function name and arguments every time it's called.
  2. Write a @validate_positive decorator that raises ValueError if any numeric argument is negative.
  3. Write a context manager cd(path) that changes into a folder (os.chdir) and always changes back afterwards. Test it with os.getcwd().
Python · editable
✎ Check your understanding

1.What does @timed above a function definition mean?

2.Why use functools.wraps in a decorator?

3.When does the cleanup code in a context manager run?

← Iterators and generators