CIPHERCODE.AI · PYTHON ADVANCED

Production-grade Python

Learn how Python really works underneath, then use that knowledge to build fast, safe, shippable software.

  • 9 modules
  • ~10 hours
  • 3 projects

What you will be able to do

  • Explain the iterator protocol and build lazy, memory-safe data pipelines with generators
  • Write decorators and closures, including decorators that take arguments, without losing function metadata
  • Manage files, locks, connections and transactions safely with context managers
  • Choose correctly between threads, processes and asyncio, and explain the GIL honestly
  • Write asyncio programs with tasks, timeouts, semaphores and structured concurrency
  • Model data with type hints, protocols, dataclasses, enums and validated models, and check them with mypy
  • Profile before optimising, and pick data structures and algorithms by measured evidence
  • Use descriptors, __init_subclass__, ABCs and metaclasses, and know when not to
  • Package, configure, log, containerise and ship a Python service with automated checks

Before you start

  • Classes, inheritance and special methods such as __init__ and __repr__
  • List, dict and set comprehensions, and functions with *args and **kwargs
  • Modules, packages, pip and virtual environments
  • Basic testing with pytest or unittest

For learners who are comfortable with classes, comprehensions, modules, virtual environments and basic testing, and want to write professional-grade Python.

At the intermediate level you learned to write programs that work. At this level you learn why they work, and how to make them work under pressure: millions of log lines, hundreds of simultaneous network calls, teammates who will read your code next year, and servers that must not crash at 3 a.m.

Each module takes one deep idea (iterators, decorators, context managers, concurrency, asyncio, types, performance, the data model, and packaging) and explains it from the inside out. You will see the protocol behind the syntax, build a small realistic system with it, break it on purpose, and read the real error messages. Every code sample on this page was executed, and the output shown is what Python actually printed.

Module 1

Iterators and generators

Understand the protocol behind every for loop, then use generators to process unlimited data in constant memory.

About 70 minutes

Every for loop you have ever written relies on a small, precise contract called the iterator protocol. Once you know that contract, generators, lazy pipelines, zip, enumerate, file reading and database cursors all stop being separate tricks and become one idea seen from different angles. This idea is also what lets a Python program handle a 50 GB log file on a laptop with 8 GB of RAM.

What a for loop really does

When Python meets for item in thing:, it does two things. First it calls iter(thing), which returns an iterator. Then it calls next(iterator) again and again, assigning each result to item, until next raises StopIteration. That exception is not an error here; it is the signal that says “no more values”, and the loop swallows it quietly. You can run the same steps by hand:

manual_iteration.py
logs = ["INFO start", "WARN disk 91%", "ERROR db timeout"]

# iter() asks the list for an iterator object.
it = iter(logs)

# Each next() call advances the iterator by exactly one step.
print(next(it))
print(next(it))
print(next(it))

# The list had three items, so a fourth call raises StopIteration.
# A for loop catches this exception for you.
try:
    next(it)
except StopIteration:
    print("exhausted")
The iterator remembers its position between calls. The list itself does not: the list is just storage, the iterator is the cursor moving over it.

Iterable versus iterator

These two words are used loosely, and mixing them up causes real bugs. The difference is small but important:

TermMust implementRemembers position?Examples
Iterable__iter__() returning an iteratorNolist, tuple, str, dict, set, range, file objects
Iterator__next__() and __iter__() returning itselfYesiter(list), generators, zip(), map(), open() file objects

An iterable can be looped over many times because each iter() call gives a fresh iterator. An iterator can only be used once: when it is exhausted, it stays exhausted. That is why you can loop over a list forever but only once over a zip object.

Building an iterator by hand

To create your own iterator, write a class with __iter__ and __next__. Walk through the example below line by line. __init__ stores the starting state. __iter__ returns self, because an iterator is its own iterable. __next__ checks whether there is anything left; if not it raises StopIteration; otherwise it produces the current value and updates the state for next time.

countdown_iterator.py
class Countdown:
    """An iterator: it stores state and hands out one value per call."""

    def __init__(self, start):
        self.current = start

    def __iter__(self):
        # An iterator is its own iterable, so it returns itself.
        return self

    def __next__(self):
        if self.current <= 0:
            raise StopIteration          # signal: nothing left
        value = self.current
        self.current -= 1                # update state for the next call
        return value


timer = Countdown(3)
print(list(timer))    # list() drives the iterator until it is exhausted
print(list(timer))    # the same object again: already exhausted, so empty
The second list(timer) is empty. This is the single most common iterator surprise, and you will meet it again with generators.

Generators: iterators without the boilerplate

Writing a class for every iterator is tedious, so Python gives you a shortcut. Any function that contains the keyword yield becomes a generator function. Calling it does not run the body. It returns a generator object, which is a ready-made iterator. Each next() call runs the body until the next yield, hands that value out, and freezes the function exactly where it is, including all local variables. The next call thaws it and carries on from that line.

generator_is_lazy.py
def countdown(start):
    print("generator body starts")
    while start > 0:
        yield start              # hand a value out and freeze here
        start -= 1               # resumes on this line at the next next()
    print("generator body ends")


gen = countdown(2)
print("created, nothing ran yet")     # no 'body starts' message yet!
print(next(gen))                      # runs until the first yield
print(next(gen))                      # resumes, loops once, yields again
try:
    next(gen)                         # loop ends, body finishes
except StopIteration:
    print("StopIteration raised")     # falling off the end raises it for you
Read the output top to bottom and match every line to the code. Nothing in the body runs until the first next(), and when the function ends Python raises StopIteration automatically.

Generator expressions and the memory difference

A list comprehension uses square brackets and builds the whole list immediately. Swap the brackets for parentheses and you get a generator expression, which builds nothing until you iterate it. When you only need to consume the values once, for example inside sum(), max(), any() or ",".join(), a generator expression is the better choice. You can even drop the extra parentheses when it is the only argument: sum(n * n for n in data).

memory_comparison.py
import sys

# Builds one million integers and keeps all of them alive at once.
big_list = [n * n for n in range(1_000_000)]

# Builds nothing yet: only a small generator object exists.
lazy = (n * n for n in range(1_000_000))

# sys.getsizeof reports the container itself (not the ints inside it),
# but the contrast is still dramatic.
print("list is over 1 MB:", sys.getsizeof(big_list) > 1_000_000)
print("generator is under 1 KB:", sys.getsizeof(lazy) < 1_000)

# Both give the same answer, but the generator never stored the values.
print(sum(big_list) == sum(lazy))

Lazy pipelines: the real payoff

The most powerful use of generators is chaining them into a pipeline, like stations on a factory line. Each stage takes an iterator in and yields an iterator out. Because every stage is lazy, the first record travels the whole pipeline before the second record is even read. Nothing is ever held in bulk. Here is a tiny log processor with three stages. Notice how each function does exactly one job, so you can test, reorder or replace stages independently.

log_pipeline.py
def read_lines(text):
    """Stage 1: produce raw lines one at a time."""
    for line in text.splitlines():
        yield line


def parse(lines):
    """Stage 2: turn 'LEVEL message...' into a dictionary."""
    for line in lines:
        level, _, message = line.partition(" ")
        yield {"level": level, "message": message}


def only(levels, records):
    """Stage 3: keep only the severities we care about."""
    for record in records:
        if record["level"] in levels:
            yield record


raw = """INFO boot ok
WARN disk 91%
INFO user login
ERROR db timeout
ERROR payment failed"""

# Nothing runs when we build the chain; it only runs inside the for loop.
pipeline = only({"WARN", "ERROR"}, parse(read_lines(raw)))
for rec in pipeline:
    print(rec["level"], "->", rec["message"])
To process a real file, replace raw.splitlines() with the file object itself. A file is already a lazy iterator of lines, so memory stays flat even for huge files.

yield from, send() and close()

yield from other hands control to another iterable and passes every value it produces straight out to your caller. It replaces a for x in other: yield x loop and also forwards send(), throw() and return values correctly. It is ideal for recursion, such as walking a directory tree.

Generators can also receive values. The expression value = yield result hands result out and, when someone calls gen.send(x), resumes with value set to x. You must “prime” such a generator with one next() call first, to advance it to the first yield. Finally, gen.close() raises GeneratorExit at the paused yield so that any finally block inside gets to run.

yield_from_and_send.py
# --- yield from: recursive directory-style walk -------------------
def walk(tree, depth=0):
    for name, children in tree.items():
        yield "  " * depth + name
        yield from walk(children, depth + 1)    # delegate to the sub-generator


project = {"app": {"core": {}, "api": {"routes": {}}}, "tests": {}}
for line in walk(project):
    print(line)

print("---")


# --- send(): a generator that receives values ----------------------
def running_average():
    total = 0.0
    count = 0
    average = None
    while True:
        value = yield average       # hand out the average, wait for a number
        total += value
        count += 1
        average = total / count


avg = running_average()
next(avg)                 # prime: run up to the first yield
print(avg.send(10))
print(avg.send(20))
print(avg.send(60))
avg.close()               # raises GeneratorExit inside, ending it cleanly

Common errors and how to read them

  • TypeError: 'int' object is not iterable: you passed a number where an iterable was needed, for example for i in 5. You probably meant range(5).
  • TypeError: can't send non-None value to a just-started generator: you called send(value) before priming. Call next(gen) first.
  • RuntimeError: generator raised StopIteration: since Python 3.7, a stray StopIteration escaping from inside a generator body is turned into a RuntimeError (PEP 479). End a generator with return, never by raising StopIteration yourself.
  • An empty result on the second pass: the generator was already exhausted. Create a new one.

When not to use a generator

Generators trade convenience for restrictions. Use a plain list when you need random access, the length, several passes over the same data, or slicing. Use a list when the data is small, because the clarity is worth more than the saved bytes. And remember that errors inside a lazy pipeline surface late: a bad line may only blow up when the consumer reaches it, far from where the pipeline was built. That is the price of laziness, and it is usually worth paying for large or streaming data.

Remember this

  • A for loop calls iter() once, then next() repeatedly until StopIteration.
  • An iterable produces fresh iterators; an iterator remembers its position and is single-use.
  • A function containing yield returns a generator; its body only runs when you call next().
  • Generator expressions and pipelines keep memory flat, no matter how large the data.
  • yield from delegates to a sub-iterator; send() and close() let you talk to a running generator.

Your turn

Write a generator batched(items, size) that yields lists of at most size items. For example batched(range(7), 3) should produce [0, 1, 2], [3, 4, 5], [6]. It must work on any iterable and never build the full input as a list. This is the same pattern used to insert database rows in chunks.

Keep one list called batch. Append each item, and when its length reaches size, yield it and start a new empty list. Do not forget the leftover items after the loop ends.

solution.py
def batched(items, size):
    batch = []
    for item in items:
        batch.append(item)
        if len(batch) == size:
            yield batch          # hand out a full batch
            batch = []           # start a fresh one
    if batch:                    # leftover items that did not fill a batch
        yield batch


print(list(batched(range(7), 3)))

Check yourself

What does a for loop call first on the object it loops over?

You write gen = (n for n in range(3)), then run list(gen) twice. What does the second call return?

When does the body of a generator function start running?

Ask the CipherCode AI tutor

Act as my Python tutor. I understand for loops and list comprehensions. Explain the iterator protocol and generators using a new real-world example (not a countdown), then give me 3 small exercises with increasing difficulty and check my answers one at a time.

Next module

Module 2

Decorators and closures

Learn how functions can capture state and wrap other functions, then build the logging, retry, registry and caching decorators used in real codebases.

About 75 minutes

You have probably typed @something above a function many times: @property, @staticmethod, @app.route(...), @pytest.fixture. A decorator looks like magic until you see that it is built from just three ordinary ideas: functions are objects, functions can be defined inside other functions, and inner functions can remember variables from the function that created them. That last idea is called a closure, and it is where we start.

Closures: functions that remember

When an inner function uses a variable from its enclosing function, Python keeps that variable alive in a small storage box called a cell, even after the outer function has returned. The inner function carries the cell with it. In the example below, make_counter finishes running immediately, yet hits still remembers count. Each call to make_counter creates a brand-new, independent cell, so hits and other do not interfere.

One detail: assigning to a captured variable would normally create a new local variable. To say “I mean the outer one”, declare it with nonlocal. Reading a captured variable needs no declaration.

closure_counter.py
def make_counter(start=0):
    count = start                     # lives in a cell, not on the stack

    def increment(step=1):
        nonlocal count                # rebind the outer variable, not a new local
        count += step
        return count

    return increment                  # make_counter ends, but count survives


hits = make_counter()
print(hits(), hits(), hits(5))        # state accumulates between calls
other = make_counter(100)             # a separate closure with its own cell
print(other())

# You can even inspect the captured cell directly.
print(hits.__closure__[0].cell_contents)

# --- The classic late-binding trap -------------------------------
# Closures capture the VARIABLE, not its value at that moment.
funcs = [lambda: i for i in range(3)]
print([f() for f in funcs])           # all three see the final i

# Fix: freeze the current value as a default argument.
funcs = [lambda i=i: i for i in range(3)]
print([f() for f in funcs])
In the trap, all three lambdas share one variable i, which ends at 2. Default arguments are evaluated immediately, which is why i=i fixes it.

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

Now combine closures with the idea that functions are values. A decorator receives a function, defines a wrapper function that adds behaviour around the call, and returns the wrapper. The line @log_calls above def apply_discount is nothing but shorthand for apply_discount = log_calls(apply_discount) executed right after the function is defined.

Look at the structure in the example: the wrapper accepts *args, **kwargs so it works for any function signature, calls the original, and returns its result. Forgetting that final return is the number one decorator bug, because the decorated function would then always return None.

log_calls.py
import functools


def log_calls(func):
    @functools.wraps(func)                      # copy name, docstring, etc.
    def wrapper(*args, **kwargs):
        shown = ", ".join(
            [repr(a) for a in args] + [f"{k}={v!r}" for k, v in kwargs.items()]
        )
        print(f"-> {func.__name__}({shown})")
        result = func(*args, **kwargs)          # call the real function
        print(f"<- {func.__name__} returned {result!r}")
        return result                           # never forget this line
    return wrapper


@log_calls                                      # same as: apply_discount = log_calls(apply_discount)
def apply_discount(price, percent=10):
    """Return price after discount."""
    return round(price * (1 - percent / 100), 2)


apply_discount(200, percent=25)
print(apply_discount.__name__)                  # still the original name
print(apply_discount.__doc__)                   # still the original docstring
Remove the @functools.wraps(func) line and the last two prints show wrapper and None. That breaks debuggers, documentation tools and anything that inspects function names.

Decorators that take arguments

To write @retry(times=3), you need one more layer. retry(times=3) is a normal call that returns the actual decorator, and that decorator is then applied to your function. So there are three nested levels: the factory receives the settings, the decorator receives the function, and the wrapper receives the call arguments. The wrapper uses closures to read times and exceptions from the outermost level.

retry_decorator.py
import functools


def retry(times=3, exceptions=(Exception,)):       # level 1: the settings
    def decorator(func):                           # level 2: the function
        @functools.wraps(func)
        def wrapper(*args, **kwargs):              # level 3: each call
            for attempt in range(1, times + 1):
                try:
                    return func(*args, **kwargs)
                except exceptions as exc:
                    print(f"attempt {attempt} failed: {exc}")
                    if attempt == times:
                        raise                      # out of attempts: re-raise
        return wrapper
    return decorator


calls = {"n": 0}


@retry(times=3, exceptions=(ConnectionError,))     # only retry network errors
def fetch_status():
    calls["n"] += 1
    if calls["n"] < 3:                             # fail twice, then succeed
        raise ConnectionError("server unreachable")
    return "200 OK"


print(fetch_status())
Catching only ConnectionError is deliberate. Retrying on every Exception would also retry bugs such as a TypeError, hiding them behind pointless repeats.

Stacking order

You can apply several decorators to one function. They are applied from the bottom up (the one closest to def wraps first), but when the function is called, execution flows from the top down (the outermost wrapper runs first). Think of wrapping a gift: the inner paper goes on first, but the recipient unwraps the outer layer first.

stacking_and_registry.py
def tag(name):
    def decorator(func):
        def wrapper():
            return f"<{name}>{func()}</{name}>"
        return wrapper
    return decorator


@tag("b")          # applied second: wraps the already-wrapped function
@tag("i")          # applied first: wraps the original
def text():
    return "hi"

# Equivalent to: text = tag("b")(tag("i")(text))
print(text())


# --- Decorators that DON'T wrap: a registry ----------------------
HANDLERS = {}

def register(command):
    def decorator(func):
        HANDLERS[command] = func   # side effect: remember the function
        return func                # return the original, untouched
    return decorator


@register("ping")
def handle_ping():
    return "pong"

@register("time")
def handle_time():
    return "12:00"

print(sorted(HANDLERS))
print(HANDLERS["ping"]())


# --- Class decorators --------------------------------------------
def add_repr(cls):
    """Give any class a readable __repr__ built from its __init__ arguments."""
    code = cls.__init__.__code__
    fields = code.co_varnames[1:code.co_argcount]     # skip 'self'

    def __repr__(self):
        body = ", ".join(f"{n}={getattr(self, n)!r}" for n in fields)
        return f"{cls.__name__}({body})"

    cls.__repr__ = __repr__
    return cls


@add_repr
class Job:
    def __init__(self, name, priority):
        self.name = name
        self.priority = priority


print(Job("backup", 2))
Decorators do not have to wrap anything. The registry decorator only records the function and hands it back, which is how web frameworks collect routes, and how test runners collect tests.

Decorators you get for free in functools

functools.lru_cache remembers the results of a function for each distinct set of arguments, a technique called memoisation. It turns exponential recursion into linear work. The arguments must be hashable, and the function should be pure (the same input always gives the same output with no side effects), otherwise you cache stale or wrong answers. functools.cache (Python 3.9+) is the same thing with no size limit. functools.singledispatch lets one function name behave differently depending on the type of its first argument, replacing long isinstance chains.

functools_tools.py
from functools import lru_cache, singledispatch


@lru_cache(maxsize=None)
def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)


print(fib(60))             # instant; without the cache this would take hours
print(fib.cache_info())    # hits = answers reused, misses = answers computed


@singledispatch
def to_json(value):
    # Fallback for any type we have not registered.
    raise TypeError(f"cannot serialise {type(value).__name__}")


@to_json.register
def _(value: int):                 # the type annotation selects the type
    return str(value)


@to_json.register
def _(value: str):
    return f'"{value}"'


@to_json.register
def _(value: list):
    return "[" + ", ".join(to_json(v) for v in value) + "]"


print(to_json([1, "two", [3]]))

Trade-offs and common mistakes

  • Forgetting parentheses: @retry instead of @retry() passes the function as times. The result is a confusing TypeError later. If your decorator takes arguments, always call it, even with none.
  • Hidden behaviour: too many stacked decorators make it hard to tell what a call actually does. Keep stacks short and document their order.
  • Caching impure functions: lru_cache on a function that reads a file or the clock returns stale data forever. Cache only pure functions, or clear with fib.cache_clear().
  • Methods and lru_cache: the cache holds a reference to self, which can keep objects alive and leak memory. Prefer caching module-level functions.
  • Debuggability: if you see an error inside wrapper, look one frame up the traceback to find your real function.

Remember this

  • A closure is an inner function that keeps the variables it uses alive after the outer function returns.
  • @decorator above def f means f = decorator(f); the wrapper should accept *args, **kwargs and return the result.
  • Always add @functools.wraps(func) so name, docstring and metadata survive.
  • A decorator with arguments has three levels: factory, decorator, wrapper.
  • Stacked decorators wrap bottom-up but execute top-down; use lru_cache only on pure functions.

Your turn

Write a decorator count_calls that counts how many times the decorated function has been called and exposes the count as func.calls. Decorate a function square(x), call it twice, and print square.calls. Make sure the decorated function keeps its name and docstring.

Functions are objects, so you can attach attributes to them: set <code>wrapper.calls = 0</code> after defining the wrapper, and increment <code>wrapper.calls</code> inside it.

solution.py
import functools


def count_calls(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        wrapper.calls += 1            # the wrapper itself stores the counter
        return func(*args, **kwargs)
    wrapper.calls = 0                 # initialise the attribute once
    return wrapper


@count_calls
def square(x):
    return x * x


square(2)
square(3)
print(square.calls)

Check yourself

What does @log_calls above def work(): ... do?

Two decorators are stacked: @a on top of @b on top of def f. Which is applied to f first?

Why should a decorator's wrapper use @functools.wraps(func)?

Ask the CipherCode AI tutor

Act as my Python tutor. Explain closures and decorators with a fresh real-world example (such as rate limiting or permission checks). Then ask me to write a decorator with arguments, review my code line by line, and point out any missing functools.wraps or return statements.

Next module

Module 3

Context managers and resource safety

Guarantee that files, locks, connections and transactions are always cleaned up, even when your code crashes halfway through.

About 60 minutes

Programs constantly borrow things: open files, database connections, network sockets, locks, temporary directories. Every borrowed thing must be given back, even if an exception is thrown in the middle. If you forget, files stay open, locks stay held and your service slowly runs out of file handles. The with statement is Python's answer, and the machinery behind it is called the context manager protocol.

The problem with manual cleanup

The naive pattern is f = open(path), work with it, then f.close(). If anything between those lines raises an exception, the close() never runs. The fix is try/finally, because finally always executes. It works but is noisy, easy to forget, and has to be repeated everywhere. A context manager packages the “set up, then always tear down” pair into one reusable object, and with applies it in a single readable line.

The protocol: __enter__ and __exit__

An object is a context manager if it has two methods. __enter__(self) runs when the block starts; whatever it returns is bound to the name after as. __exit__(self, exc_type, exc, tb) runs when the block ends for any reason. If the block finished normally, all three arguments are None. If an exception escaped, they describe it. The return value of __exit__ matters: return a true value and the exception is swallowed; return false (or nothing) and it continues to propagate. Walk through this example and match each printed line to the method that produced it.

connection_manager.py
class Connection:
    def __init__(self, name):
        self.name = name

    def __enter__(self):
        print(f"open {self.name}")
        return self                       # this becomes the 'as' variable

    def __exit__(self, exc_type, exc, tb):
        error = exc_type.__name__ if exc_type else None
        print(f"close {self.name} (error: {error})")
        return False                      # False: do NOT swallow the exception

    def query(self, sql):
        print(f"run {sql}")
        if "DROP" in sql:
            raise PermissionError("DROP is blocked")


# Normal path: __exit__ receives (None, None, None).
with Connection("db1") as conn:
    conn.query("SELECT 1")

print("---")

# Failure path: __exit__ still runs, then the exception continues outward.
try:
    with Connection("db2") as conn:
        conn.query("DROP TABLE users")
except PermissionError as e:
    print("caught:", e)
Notice that close db2 is printed before caught:. Cleanup happens at the moment the block is left, not when the exception is finally handled.

Swallowing exceptions on purpose

Sometimes an error is expected and harmless, such as deleting a file that may already be gone. Writing try/except/pass works, but contextlib.suppress says your intent more clearly: “these specific errors are fine here”. Name only the exceptions you truly expect. Suppressing Exception broadly hides real bugs.

suppress_example.py
import os
from contextlib import suppress

# The file does not exist, so os.remove raises FileNotFoundError.
# suppress() catches exactly that exception and nothing else.
with suppress(FileNotFoundError):
    os.remove("does-not-exist.tmp")

print("continued")

# A different error is NOT suppressed, which is what we want:
try:
    with suppress(FileNotFoundError):
        int("not a number")          # raises ValueError
except ValueError:
    print("ValueError still propagated")

Writing context managers with @contextmanager

Writing a class with two methods is fine, but for most cases a generator is shorter. Decorate a generator function that has exactly one yield with @contextmanager. Everything before the yield is the setup (__enter__). The yielded value becomes the as variable. Everything after the yield is the teardown (__exit__). If the body raises an exception, it is thrown into the generator at the yield line, so you can catch it with try/except around the yield.

The example below implements a tiny transaction: it snapshots a dictionary, lets the block modify it, and if anything fails it restores the snapshot. This all-or-nothing behaviour is exactly how database transactions work, and the same shape is used for commit() and rollback() in real database libraries.

transaction.py
from contextlib import contextmanager


@contextmanager
def transaction(store):
    snapshot = dict(store)            # setup: remember the starting state
    print("begin")
    try:
        yield store                   # the with-block runs here
    except Exception:
        store.clear()                 # failure: put everything back
        store.update(snapshot)
        print("rollback")
        raise                         # re-raise so the caller knows
    else:
        print("commit")               # success: keep the changes


accounts = {"alice": 100, "bob": 50}

# Successful transfer: both changes are kept.
with transaction(accounts) as acc:
    acc["alice"] -= 30
    acc["bob"] += 30
print(accounts)

# Failing transfer: the first change happens, then the error rolls it back.
try:
    with transaction(accounts) as acc:
        acc["alice"] -= 500
        if acc["alice"] < 0:
            raise ValueError("insufficient funds")
except ValueError as e:
    print("error:", e)
print(accounts)                       # unchanged by the failed attempt
The second balance print proves the rollback: even though alice was reduced inside the block, the dictionary is back to its earlier state.

Several resources at once with ExitStack

Stacking with a, b, c: works when you know the count in advance. When the number of resources is only known at run time, for example “open every file in this list”, use contextlib.ExitStack. You register each context manager with enter_context, and when the block ends the stack closes everything in reverse order (last opened, first closed), even if one of the closings fails. That reverse order mirrors how you would unpack a stack of boxes.

exit_stack.py
from contextlib import ExitStack, contextmanager


@contextmanager
def open_resource(name):
    print(f"open {name}")
    try:
        yield name
    finally:
        print(f"close {name}")        # runs no matter what


names = ["a.log", "b.log", "c.log"]

with ExitStack() as stack:
    # The number of resources is decided at run time.
    files = [stack.enter_context(open_resource(n)) for n in names]
    print("working with", files)
# Leaving the block closes c.log, then b.log, then a.log (reverse order).

A reusable utility: temporary environment variables

Context managers shine for “change something temporarily, then restore it”. Tests that need a particular environment variable, scripts that temporarily change the working directory, and code that swaps a setting for one operation all fit. The pattern is always: save the old value, change it, yield, restore in finally.

temp_env.py
import os
from contextlib import contextmanager


@contextmanager
def temp_env(**values):
    # Remember what each variable was (None means "was not set").
    old = {key: os.environ.get(key) for key in values}
    os.environ.update(values)             # values must be strings
    try:
        yield
    finally:
        for key, previous in old.items():
            if previous is None:
                os.environ.pop(key, None) # it did not exist before: remove it
            else:
                os.environ[key] = previous


with temp_env(APP_MODE="test"):
    print(os.environ["APP_MODE"])         # visible only inside the block
print(os.environ.get("APP_MODE"))         # restored: not set any more

Where you will meet context managers

  • open() for files, and tempfile.TemporaryDirectory() for scratch space that disappears afterwards.
  • threading.Lock(): with lock: acquires and always releases, avoiding deadlocks caused by a forgotten release().
  • Database libraries: with connection: typically commits on success and rolls back on error.
  • async with is the same idea for coroutines, using __aenter__ and __aexit__; you will use it in the asyncio module.

When not to use one: if there is no cleanup and no paired setup, a context manager adds ceremony without value. Use a plain function. And do not keep a resource open beyond its block by smuggling the as variable out: a file object used after its with block raises ValueError: I/O operation on closed file.

Remember this

  • with guarantees teardown by calling __exit__ whether the block succeeds or raises.
  • __enter__ returns the value for 'as'; a true return from __exit__ swallows the exception.
  • @contextmanager turns a generator with one yield into a context manager; wrap the yield in try/finally.
  • suppress() ignores only the exceptions you name; ExitStack handles a run-time number of resources.
  • The shape 'save, change, yield, restore' fits transactions, temporary settings and locks.

Your turn

Write a context manager section(title) that prints the title and indents every message logged inside it by two more spaces, restoring the indentation on exit even if an error occurs. Use a module-level depth counter and a log(msg) helper. Nest two sections to prove the indentation stacks.

Use <code>@contextmanager</code>. Call <code>log(title)</code>, then <code>depth += 1</code> (declare it <code>global</code>), <code>yield</code> inside a <code>try</code>, and decrement in <code>finally</code>.

solution.py
from contextlib import contextmanager

depth = 0


def log(msg):
    print("  " * depth + msg)


@contextmanager
def section(title):
    global depth
    log(title)
    depth += 1
    try:
        yield
    finally:
        depth -= 1               # always restored, even after an exception


with section("deploy"):
    log("build")
    with section("migrate"):
        log("apply 001")
    log("restart")
log("done")

Check yourself

What happens if __exit__ returns True when the with-block raised an exception?

In a @contextmanager generator, where must the teardown be placed so that it runs even when the body fails?

ExitStack closes the resources it manages in which order?

Ask the CipherCode AI tutor

Act as my Python tutor. Explain context managers and the with statement using a database-transaction example. Then give me three exercises: a class-based context manager, a @contextmanager one, and one using ExitStack, and review each solution I write.

Next module

Module 4

Threads and processes

Do more than one thing at a time: know when threads help, when only processes will do, and why the GIL changes the answer.

About 60 minutes

A program that waits is wasting time. While your code waits for a web server to reply, a disk to deliver bytes or a database to answer, the CPU sits idle. Concurrency means arranging your program so that other useful work happens during those gaps, or so that several CPU cores work at once. Python gives you three tools: threads, processes and asyncio. This module covers the first two. The next module covers asyncio. Choosing correctly starts with one question: what is my program waiting for?

I/O-bound or CPU-bound?

A task is I/O-bound when most of its time is spent waiting for something outside your code: a network response, a file read, a sleep. Doubling the CPU speed would not help it, because the CPU is not the bottleneck. A task is CPU-bound when it spends its time calculating: parsing a huge file, resizing images, checking primes, training a model. For these tasks the only cure is more cores doing calculations at the same moment, or a faster algorithm. Everything else in this module follows from that split.

QuestionI/O-bound workCPU-bound work
ExampleDownload 50 web pagesCount primes below 10 million
What is the program doing most of the time?WaitingCalculating
Do threads help in standard CPython?Yes, stronglyNo, because of the GIL
Do processes help?Yes, but heavier than neededYes, this is their job

Threads and the problem of shared state

A thread is an independent line of execution inside your process. All threads share the same memory, which is both their strength (passing data is easy) and their danger (two threads can touch the same variable at once). You create one with threading.Thread(target=function), begin it with start() and wait for it to finish with join().

The classic danger is the race condition. Incrementing a counter looks like one step, but it is really three: read the value, add one, write it back. If two threads both read the old value before either writes, one increment is lost. Real races depend on tiny timing differences, so they are hard to reproduce. The example below forces the unlucky timing with a Barrier (a meeting point where both threads must arrive before either continues) so that the bug appears every single time. Then it shows the fix: a Lock, used with with so it is always released.

race_condition.py
import threading

# ---- The bug: a lost update, made deterministic ----
balance = 0
barrier = threading.Barrier(2)       # both threads must arrive before either continues


def unsafe_add():
    global balance
    seen = balance                   # step 1: read the current value
    barrier.wait()                   # both threads have now read the SAME old value
    balance = seen + 1               # step 3: write, based on a stale read


threads = [threading.Thread(target=unsafe_add) for _ in range(2)]
for t in threads:
    t.start()
for t in threads:
    t.join()                         # wait until both are finished
print("two increments, balance =", balance)


# ---- The fix: protect the read-modify-write with a Lock ----
counter = 0
lock = threading.Lock()


def safe_add(times):
    global counter
    for _ in range(times):
        with lock:                   # only one thread may be inside at a time
            counter += 1


workers = [threading.Thread(target=safe_add, args=(10_000,)) for _ in range(4)]
for w in workers:
    w.start()
for w in workers:
    w.join()
print("four threads, counter =", counter)
Line by line: each thread reads balance (0), waits at the barrier, then writes 0 + 1. Two additions produced a result of 1, because the second write overwrote the first. In the second half, with lock: makes the read, add and write one indivisible step, so 4 × 10,000 gives exactly 40,000.

A worker pool with queue.Queue

Starting one thread per task does not scale: ten thousand tasks would mean ten thousand threads. The standard pattern is a small fixed group of worker threads that pull jobs from a shared queue.Queue. The queue is already thread-safe, so you do not need your own lock around put() and get(). Workers loop forever taking jobs, and you stop them by putting one sentinel value (here None) per worker. jobs.join() blocks until every job has been marked finished with task_done().

worker_pool.py
import queue
import threading

jobs = queue.Queue()
results = []
results_lock = threading.Lock()      # list.append is safe, but this shows the habit


def worker():
    while True:
        item = jobs.get()            # blocks until a job is available
        if item is None:             # sentinel: no more work for this worker
            jobs.task_done()
            break
        value = item * item          # the "work"
        with results_lock:
            results.append((item, value))
        jobs.task_done()             # tell the queue this job is finished


workers = [threading.Thread(target=worker) for _ in range(3)]
for w in workers:
    w.start()

for n in range(1, 9):
    jobs.put(n)                      # eight jobs for three workers
for _ in workers:
    jobs.put(None)                   # one stop signal per worker

jobs.join()                          # wait until every job is done
for w in workers:
    w.join()

# Which worker handled which job is unpredictable, so sort before printing.
print(sorted(results))

The GIL, explained honestly

CPython, the standard Python, has a Global Interpreter Lock (GIL): a lock that lets only one thread run Python bytecode at a time. It exists because CPython manages memory with reference counting, and making every count update thread-safe individually would be slow and complex. The GIL is a simple, fast solution for single-threaded code, and it protects the interpreter's internals. It does not protect your own variables, which is why the race condition above still happens.

The consequences are precise. When a thread does I/O (reads a socket, waits on time.sleep, reads a file), it releases the GIL while it waits, so other threads run. Threads therefore speed up I/O-bound programs very well. When threads do CPU-bound Python work, they take turns holding the GIL, so four threads give you roughly the speed of one, sometimes slightly worse because of switching. Some C extensions such as NumPy release the GIL during heavy calculations, which is why they can use several cores from threads.

gil_check.py
import sys

# Python 3.13+ can tell you whether the GIL is active.
# Older versions do not have the function, so we fall back to True.
gil_on = getattr(sys, "_is_gil_enabled", lambda: True)()
print("GIL enabled:", gil_on)
On a normal CPython build this prints True. On a free-threaded 3.13 build it can print False.

concurrent.futures: the comfortable interface

Managing threads and queues by hand is educational but rarely necessary. The concurrent.futures module gives you pools with one shared interface. pool.map(function, items) runs the function on every item and yields the results in input order. pool.submit(function, arg) returns a Future, an object representing a result that is not ready yet; future.result() waits for it and, importantly, re-raises any exception the worker hit. The with block waits for all work to finish before leaving.

thread_pool.py
import time
from concurrent.futures import ThreadPoolExecutor


def fetch(name):
    time.sleep(0.05)                 # stand-in for a network call; the GIL is released
    return f"{name}: ok"


sites = ["alpha", "beta", "gamma", "delta"]

# map() keeps the results in the same order as the input.
with ThreadPoolExecutor(max_workers=4) as pool:
    for line in pool.map(fetch, sites):
        print(line)

# submit() returns a Future; errors inside a worker surface at result().
with ThreadPoolExecutor(max_workers=2) as pool:
    future = pool.submit(int, "x")   # int("x") fails inside the worker thread
    try:
        future.result()
    except ValueError as err:
        print("worker error re-raised:", err)
Four tasks of 0.05 seconds finish in about 0.05 seconds in total, not 0.2, because the waits overlap. That overlap is the whole benefit.

Processes for CPU-bound work

A process is a separate copy of the interpreter with its own memory and its own GIL, so processes truly run in parallel on different cores. The price is overhead: starting a process is slower than starting a thread, and data cannot be shared directly. It has to be pickled (converted to bytes), sent to the worker and unpickled. ProcessPoolExecutor has the same interface as the thread version, so switching is often a one-word change.

There is one rule you must follow: wrap the starting code in if __name__ == "__main__":. On Windows and macOS, child processes are started by importing your script afresh. Without the guard, every child would run the pool-creating code again and spawn more children. Python detects this and stops it with RuntimeError: An attempt has been made to start a new process before the current process has finished its bootstrapping phase.

process_pool.py
from concurrent.futures import ProcessPoolExecutor


def count_primes(limit):
    """CPU-bound: pure calculation, no waiting."""
    count = 0
    for n in range(2, limit):
        if all(n % d for d in range(2, int(n ** 0.5) + 1)):
            count += 1
    return count


if __name__ == "__main__":           # required so children do not re-run this block
    limits = [10_000, 20_000, 30_000]
    with ProcessPoolExecutor(max_workers=3) as pool:
        for limit, total in zip(limits, pool.map(count_primes, limits)):
            print(f"primes below {limit}: {total}")

Because arguments and results travel by pickle, only picklable things can cross the boundary. Top-level functions and ordinary data are fine. Lambdas, locally defined functions, open files, locks and database connections are not. The error you will meet is _pickle.PicklingError: Can't pickle <function <lambda> ...> or AttributeError: Can't pickle local object. The fix is to move the function to the top level of a module.

pickling_limits.py
import pickle


def cube(x):                         # a named top-level function can be pickled
    return x ** 3


square = lambda x: x * x             # a lambda cannot

print("function pickled:", len(pickle.dumps(cube)) > 0)
try:
    pickle.dumps(square)
except Exception as err:
    print("lambda failed with", type(err).__name__)

Choosing between them

  • Waiting on network, disk or a database, and the work per item is small: ThreadPoolExecutor. It is light and simple. For thousands of connections, consider asyncio (next module).
  • Heavy calculation in pure Python: ProcessPoolExecutor, sized to your core count (os.cpu_count()). Make each task big enough that the pickling cost is small by comparison.
  • Heavy calculation inside NumPy or another library that releases the GIL: threads may already be enough. Measure first.
  • Neither: if a task takes 20 ms in total, concurrency adds complexity for no gain. A better algorithm usually beats more workers.

Remember this

  • Ask first: is the task I/O-bound (waiting) or CPU-bound (calculating)? The answer picks the tool.
  • Threads share memory, so any variable several threads write to needs a Lock, or should not be shared at all.
  • The GIL lets one thread run Python bytecode at a time: threads help I/O-bound work but not CPU-bound pure Python.
  • concurrent.futures gives threads and processes one interface; map keeps input order and result() re-raises worker errors.
  • Process pools need the if __name__ == '__main__' guard and picklable functions and data.

Your turn

Build a thread-safe Counter class with an add(n) method and a value property, protected by a threading.Lock. Start 5 threads that each call add(1) 2,000 times, join them, and print the final value.

Create the lock in <code>__init__</code> and use <code>with self._lock:</code> inside <code>add</code>. Build the list of threads with a list comprehension, start them all, then join them all in a second loop.

solution.py
import threading


class Counter:
    def __init__(self):
        self._value = 0
        self._lock = threading.Lock()

    def add(self, n):
        with self._lock:             # read-modify-write is now indivisible
            self._value += n

    @property
    def value(self):
        return self._value


def run(counter):
    for _ in range(2_000):
        counter.add(1)


counter = Counter()
threads = [threading.Thread(target=run, args=(counter,)) for _ in range(5)]
for t in threads:
    t.start()
for t in threads:
    t.join()
print("final value:", counter.value)

Check yourself

Why do four threads running a pure-Python CPU-bound loop give roughly the speed of one thread in standard CPython?

What does a Lock protect you from?

Why is the if __name__ == '__main__' guard required when using ProcessPoolExecutor on Windows and macOS?

Ask the CipherCode AI tutor

Act as my Python tutor. Explain the difference between I/O-bound and CPU-bound work, and how the GIL affects threads. Give me three small tasks (download pages, count primes, resize images) and ask me to choose ThreadPoolExecutor or ProcessPoolExecutor for each, then explain whether my choice was right.

Next module

Module 5

Asyncio: thousands of waits on one thread

Write programs that juggle thousands of slow network calls on a single thread, and learn the one mistake that freezes all of them at once.

About 60 minutes

Threads are one way to wait for many things at once. asyncio is another, and it works on a different idea: cooperative multitasking. Your whole program runs on one thread. A piece of code called the event loop keeps a list of jobs. It runs one job until that job says "I am going to wait for something, someone else can have a turn", then it picks the next job. Nothing is ever interrupted in the middle of a line, so there are no lost updates and far fewer locks. The price is that every job must volunteer to pause.

Think of one chef cooking five dishes. The chef never stands and stares at a pot of rice. They put it on, switch to chopping, come back when the timer rings. One person, five dishes, no extra kitchens. That is asyncio. It shines when you wait on the network or disk for a long time and have many things in flight: web crawlers, chat servers, API gateways, anything that calls other services.

Coroutines and await

A function defined with async def is a coroutine function. Calling it does not run its body. It returns a coroutine object, a paused job waiting for the event loop. You run it in one of two ways: hand it to asyncio.run() from ordinary code, or write await in front of it from inside another coroutine. The word await means two things at once: start this job and wait for its result, and while I wait, the loop may run other jobs. Those are the only places where switching can happen, so you can read an async function and see every possible pause point.

The first example shows both facts. Calling greet() gives a coroutine object. Then the second half compares awaiting three jobs one after another with starting them together using asyncio.gather(). The sleeps are tiny so the script finishes quickly, but the pattern is exactly what you would use with real network calls.

basics.py
import asyncio
import time


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


coro = greet("Asha")
print(type(coro).__name__)   # calling did NOT run the body: it made a coroutine object
coro.close()                 # discard it cleanly so Python does not warn "never awaited"


async def fetch(name, delay):
    await asyncio.sleep(delay)          # stands in for a slow network call
    print("done", name)
    return name.upper()


async def one_after_another():
    start = time.perf_counter()
    results = []
    for name in ["a", "b", "c"]:
        results.append(await fetch(name, 0.05))   # waits for each before starting the next
    return results, time.perf_counter() - start


async def all_together():
    start = time.perf_counter()
    results = await asyncio.gather(               # starts all three, waits for all three
        fetch("x", 0.05), fetch("y", 0.03), fetch("z", 0.01)
    )
    return results, time.perf_counter() - start


seq, t_seq = asyncio.run(one_after_another())
con, t_con = asyncio.run(all_together())
print(seq, con)
print("together is at least 2x faster:", t_con * 2 < t_seq)
Sequential awaiting takes about 0.15 s (3 × 0.05). gather takes about 0.05 s, the length of the slowest job, because all three waits overlap. Notice the finishing order is z, y, x: results come back in the order you passed the jobs, but the jobs themselves finish whenever they finish.

Tasks: starting work without waiting for it

await job() runs a job and waits right there. Sometimes you want to start a job, carry on with other work, and collect the result later. asyncio.create_task(job()) wraps the coroutine in a Task and schedules it on the loop immediately. The task begins running the next time your current code reaches an await. You can then await the task later to get its result, or call task.cancel() to stop it. gather() creates tasks for you behind the scenes.

To see switching happen, the next example uses await asyncio.sleep(0). Sleeping for zero seconds does no waiting at all. It simply says "let someone else have a turn", which makes the interleaving visible and perfectly repeatable.

tasks.py
import asyncio


async def worker(name, steps):
    for i in range(steps):
        print(name, "step", i)
        await asyncio.sleep(0)       # pause point: hand control back to the event loop


async def main():
    a = asyncio.create_task(worker("A", 3))
    b = asyncio.create_task(worker("B", 3))
    print("tasks created, neither has run yet")   # no await has happened, so no switching yet
    await a                                       # now the loop is free to run A and B
    await b


asyncio.run(main())
Line by line: create_task only schedules. The first print runs before either worker starts, because main has not yielded yet. At await a the loop begins A, which prints and yields at sleep(0); the loop then runs B, then returns to A, and so on. They alternate perfectly, on one thread, with no locks.

Timeouts, errors and cancellation

Network calls hang. Always put a limit on them. asyncio.wait_for(job, timeout=seconds) cancels the job and raises asyncio.TimeoutError if it takes too long. Python 3.11 added the nicer async with asyncio.timeout(seconds): block that limits everything inside it. Cancellation works by raising asyncio.CancelledError inside the job at its current await, so try/finally blocks in the job still run and clean up. Never swallow CancelledError with a bare except.

Errors need a decision. By default gather() raises the first exception and leaves the other jobs running unobserved. If you would rather collect everything, pass return_exceptions=True: failures come back as exception objects in the results list, in order, and you check each one.

timeouts.py
import asyncio


async def slow():
    await asyncio.sleep(1)
    return "finished"


async def flaky(n):
    await asyncio.sleep(0.01)
    if n == 2:
        raise ValueError(f"job {n} failed")
    return f"job {n} ok"


async def main():
    try:
        await asyncio.wait_for(slow(), timeout=0.05)     # gives up after 50 ms
    except asyncio.TimeoutError:
        print("timed out, slow() was cancelled")

    # Collect every outcome instead of stopping at the first failure
    results = await asyncio.gather(*(flaky(n) for n in range(4)), return_exceptions=True)
    for r in results:
        print(repr(r) if isinstance(r, Exception) else r)


asyncio.run(main())
*(flaky(n) for n in range(4)) unpacks four coroutines as separate arguments. With return_exceptions=True the failure at index 2 appears in place as a ValueError object, and the other three results are untouched.

TaskGroup: structured concurrency (Python 3.11+)

gather has an awkward weakness: if one job fails, the others keep running with nobody watching them. Python 3.11 added asyncio.TaskGroup, which follows the rule of structured concurrency: every job started inside the async with block must finish before the block ends, and if any job fails, the rest are cancelled. Failures arrive together as an ExceptionGroup, which you catch with except*. This is the recommended style on modern Python. The example below needs 3.11 or newer, so its output is shown as a recorded run.

taskgroup.py
import asyncio


async def job(n):
    await asyncio.sleep(0.01 * n)
    if n == 2:
        raise RuntimeError("job 2 broke")
    return n


async def main():
    tasks = []
    try:
        async with asyncio.TaskGroup() as tg:        # all tasks must finish before leaving
            for n in (1, 2, 3):
                tasks.append(tg.create_task(job(n)))
    except* RuntimeError as group:                   # failures arrive as an ExceptionGroup
        print("group failed:", [str(e) for e in group.exceptions])
    print("job 1 result:", tasks[0].result())
    print("job 3 cancelled:", tasks[2].cancelled())


asyncio.run(main())
Job 1 finishes first (10 ms). Job 2 fails at 20 ms, so the group cancels job 3 before its 30 ms are up. With plain gather job 3 would have carried on unsupervised.

Limiting concurrency with a semaphore

Starting 10,000 downloads at once will exhaust file handles, overwhelm the server and get you rate-limited. An asyncio.Semaphore(n) is a counter of permits. async with sem: takes a permit, waiting if none are left, and returns it when the block ends. At most n jobs are inside the block at once, however many tasks you created.

semaphore.py
import asyncio

active = 0     # how many calls are inside the block right now
peak = 0       # the most we ever saw at once


async def call_api(sem, n):
    global active, peak
    async with sem:                      # wait here if 3 calls are already running
        active += 1
        peak = max(peak, active)
        await asyncio.sleep(0.01)        # the "request"
        active -= 1


async def main():
    sem = asyncio.Semaphore(3)
    await asyncio.gather(*(call_api(sem, n) for n in range(10)))
    print("10 calls made, peak concurrent calls:", peak)


asyncio.run(main())
Ten tasks exist from the start, but only three ever hold a permit. The other seven wait their turn. The same pattern is how you stay under an API's rate limit.

The blocking-call trap

Here is the rule that matters most: one slow synchronous call freezes every job on the loop. The event loop only regains control at an await. If you call time.sleep(5), requests.get(...), a big file read or a heavy calculation, the loop is stuck inside it, and your thousand other connections get no service for five seconds. Use async versions (asyncio.sleep, httpx or aiohttp instead of requests), or push the blocking work to a thread with asyncio.to_thread() (Python 3.9+) so the loop stays free. For heavy CPU work, use a process pool; asyncio does nothing for CPU-bound code.

blocking.py
import asyncio
import time

ticks = 0


async def heartbeat():
    """A healthy loop runs this every 10 ms."""
    global ticks
    while True:
        await asyncio.sleep(0.01)
        ticks += 1


def blocking_job():
    time.sleep(0.15)                      # an ordinary blocking call


async def main():
    global ticks
    beat = asyncio.create_task(heartbeat())
    await asyncio.sleep(0)                # let the heartbeat start
    ticks = 0

    blocking_job()                        # BAD: runs on the loop thread and freezes it
    print("heartbeats while blocked:", ticks)

    await asyncio.to_thread(blocking_job)  # GOOD: runs in a worker thread
    print("heartbeat kept running in a thread:", ticks >= 5)
    beat.cancel()


asyncio.run(main())
During the direct call the heartbeat cannot run at all, so the count stays at 0. During to_thread the loop is free, and about 15 heartbeats fit into the 150 ms.

Async, threads or processes?

SituationBest toolReason
Thousands of network calls, libraries with async supportasyncioCheapest per connection; no locks needed between awaits
A few dozen blocking calls, library has no async versionThreads (ThreadPoolExecutor)Simple, and the GIL is released while waiting on I/O
Heavy calculation on many coresProcesses (ProcessPoolExecutor)Each process has its own GIL
Small script with one or two waitsPlain synchronous codeConcurrency adds complexity you do not need

Async has a cost: it spreads. Once one function awaits, its caller must be async too, and so on up to asyncio.run(). Mixing async and blocking libraries is where most real-world bugs come from, so pick one style per program and keep the boundary clear.

Remember this

  • Calling an async def function returns a coroutine; nothing runs until you await it, schedule it as a task, or pass it to asyncio.run().
  • await is the only place the loop can switch jobs. gather() and create_task() let waits overlap, so total time is the slowest job, not the sum.
  • Always bound slow calls with a timeout and bound parallelism with a Semaphore.
  • Prefer TaskGroup (3.11+) for structured concurrency; use return_exceptions=True with gather when you want every outcome.
  • A blocking call inside a coroutine freezes the whole loop. Use async libraries, or asyncio.to_thread() for blocking work.
  • asyncio helps with waiting, not calculating. CPU-bound work still needs processes.

Your turn

Simulate downloading six pages: home, about, pricing, docs, blog, contact. Write an async fake_download(sem, name) that waits 0.02 s and returns name + ".html". Download all six at most two at a time using a semaphore, print the results in input order, and print the peak number of simultaneous downloads (it should be 2).

Create <code>asyncio.Semaphore(2)</code> inside <code>main()</code>. Use <code>async with sem:</code> around the sleep, and track <code>active</code> and <code>peak</code> counters like the semaphore example. <code>gather</code> returns results in the order you passed the coroutines.

solution.py
import asyncio

active = 0
peak = 0


async def fake_download(sem, name):
    global active, peak
    async with sem:
        active += 1
        peak = max(peak, active)
        await asyncio.sleep(0.02)
        active -= 1
    return name + ".html"


async def main():
    sem = asyncio.Semaphore(2)
    names = ["home", "about", "pricing", "docs", "blog", "contact"]
    pages = await asyncio.gather(*(fake_download(sem, n) for n in names))
    print(pages)
    print("peak:", peak)


asyncio.run(main())

Check yourself

What happens when you call an async def function without await, for example fetch("a", 1) on its own line?

Why does calling time.sleep(5) inside a coroutine hurt a server handling 1,000 connections?

Three jobs each wait 0.05 s. Roughly how long does asyncio.gather(job1, job2, job3) take?

Ask the CipherCode AI tutor

Act as my Python tutor. Explain the asyncio event loop with a kitchen analogy, then give me a small program that mixes a blocking call with async code and ask me to find why it is slow. After I answer, show me how asyncio.to_thread or a semaphore fixes it, and explain when I should use threads instead of asyncio.

Next module

Module 6

Typing and data modelling

Describe your data precisely with type hints, generics, protocols, dataclasses and enums, then let tools catch mistakes before your users do.

About 60 minutes

Python is dynamically typed: a variable can hold a number now and a string a moment later, and nothing complains until a line actually fails at run time. That freedom is wonderful for a ten-line script and painful for a ten-thousand-line codebase, where the question "what does this function expect, and what does it give back?" decides whether a change is safe. Type hints answer that question in the code itself. They are labels you attach to parameters, return values and variables. Python stores them but does not enforce them. Their readers are your teammates, your editor, and a separate program called a type checker (mypy, pyright) that reads your code without running it and reports contradictions.

Hints in practice

Annotate a parameter with a colon (prices: list[float]) and a return value with an arrow (-> float). Since Python 3.9 you can write built-in container types directly, list[int], dict[str, float], tuple[int, str], and since 3.10 you can write a choice between types with a pipe: int | None means "an integer or nothing". Older code imports List, Dict and Optional from typing; you will see both styles, and the modern one is shorter.

hints.py
def total(prices: list[float], tax: float | None = None) -> float:
    base = sum(prices)
    return base if tax is None else base * (1 + tax)


print(total([100.0, 50.0], 0.5))
print(total.__annotations__)          # hints are just data stored on the function


# Python does NOT check hints at run time: this "wrong" call runs happily.
def shout(text: str) -> str:
    return text * 2


print(shout(3))                        # prints 6, no error. A type checker would flag it.
The annotations dictionary shows that hints are ordinary objects stored in __annotations__. They cost almost nothing at run time, and they change nothing about how the program behaves. Their value is in the tooling and in the reader's understanding.

Generics: one definition, many types

Suppose you write first(items) that returns the first element. If you hint the result as int it is wrong for a list of strings, and if you hint it as object the caller loses all information. A type variable solves this: T = TypeVar("T") stands for "whatever type the caller uses", and the same T appearing in the input and output links them. A class can be generic in the same way by inheriting from Generic[T]. Python 3.12 added a shorter syntax (class Stack[T]:), but the form below works on every supported version.

generics.py
from typing import Generic, TypeVar

T = TypeVar("T")                       # a placeholder for "some type, chosen by the caller"


def first(items: list[T]) -> T:        # a list of T in, a T out: the checker links the two
    return items[0]


class Stack(Generic[T]):
    def __init__(self) -> None:
        self._items: list[T] = []

    def push(self, item: T) -> None:
        self._items.append(item)

    def pop(self) -> T:
        return self._items.pop()


names: Stack[str] = Stack()            # this stack holds strings only, as far as a checker cares
names.push("Asha")
names.push("Ravi")
print(names.pop(), first([10, 20, 30]), first(["x", "y"]))
A checker infers that first([10, 20, 30]) is an int and first(["x", "y"]) is a str, from one definition. It would reject names.push(5) because names is a Stack[str].

Protocols and TypedDict: describing shape instead of ancestry

Python programmers rely on duck typing: if it has a send() method, treat it as a notifier. A typing.Protocol lets you write that expectation down. A class matches a protocol simply by having the right methods; it does not have to inherit from anything. This is called structural typing, and it keeps modules decoupled: your function can accept any object with the right shape, including classes from libraries you do not control. Add @runtime_checkable and you can also use isinstance, which checks that the method names exist (not their signatures).

Real programs also pass dictionaries around, such as JSON from an API. A TypedDict describes which keys a dictionary has and what each value is, so a checker can catch a misspelled key. At run time it is a perfectly ordinary dict.

protocols.py
from typing import Protocol, TypedDict, runtime_checkable


@runtime_checkable
class Notifier(Protocol):
    def send(self, to: str, message: str) -> str: ...


class EmailNotifier:                   # no inheritance from Notifier anywhere
    def send(self, to, message):
        return f"email to {to}: {message}"


class SmsNotifier:
    def send(self, to, message):
        return f"sms to {to}: {message}"


def alert(channel: Notifier, who: str) -> None:
    print(channel.send(who, "build finished"))


for channel in (EmailNotifier(), SmsNotifier()):
    alert(channel, "asha@example.com")
print(isinstance(SmsNotifier(), Notifier), isinstance("text", Notifier))


class OrderRecord(TypedDict):          # the expected keys and value types of a dict
    id: int
    items: list[str]


order: OrderRecord = {"id": 7, "items": ["chai", "samosa"]}
print(order["items"], type(order).__name__)
Both notifier classes satisfy Notifier just by having send. A string has no send method, so isinstance says False. The last line proves a TypedDict is still a plain dict underneath.

Dataclasses and enums: modelling your domain

Writing __init__, __repr__ and __eq__ by hand for every record class is tedious. @dataclass generates them from annotated fields. The options worth knowing: frozen=True makes instances immutable (and hashable), order=True adds comparison methods, slots=True (3.10+) saves memory and blocks accidental new attributes, and kw_only=True (3.10+) forces keyword arguments. For mutable defaults such as lists you must use field(default_factory=list). Validation goes in __post_init__, which runs right after the generated __init__.

An Enum is a fixed set of named values. Instead of the string "shipped" that might be mistyped as "shiped" in one place, you write Status.SHIPPED, and a typo becomes an immediate AttributeError and a checker error. Use auto() when the actual values do not matter, and IntEnum when members must also behave as integers (for sorting by priority, say).

models.py
from dataclasses import dataclass, field, replace
from enum import Enum, auto


class Status(Enum):
    PENDING = auto()          # auto() assigns 1, 2, 3 ...
    SHIPPED = auto()
    DELIVERED = auto()


@dataclass(frozen=True, slots=True)   # immutable and memory-light
class Item:
    name: str
    price: float


@dataclass
class Order:
    id: int
    items: list[Item] = field(default_factory=list)   # a fresh list for every order
    status: Status = Status.PENDING

    def total(self) -> float:
        return sum(item.price for item in self.items)


order = Order(1, [Item("chai", 20.0), Item("samosa", 15.0)])
print(order)                                           # __repr__ was generated for us
print(order.total(), order.status.name, Status(2))
order.status = Status.SHIPPED

cheaper = replace(order.items[0], price=18.0)          # copy with one field changed
print(cheaper)
try:
    order.items[0].price = 1                           # frozen: assignment is refused
except Exception as err:
    print(type(err).__name__)
The printed Order(...) line comes free from @dataclass. Status(2) looks a member up by value. Because Item is frozen, you never edit one in place; replace() builds a modified copy, which is a safe style for shared data.

The mypy mindset

A type checker is a tireless reviewer that reads every line without running it. Install it with pip install mypy and run mypy yourfile.py. Start with the defaults on new files, and as the code matures turn on --strict (or strict = true in pyproject.toml) so missing annotations and loose types are reported. Run the checker in your continuous-integration pipeline next to your tests: tests prove that the cases you thought of work; the checker proves that whole classes of mistakes cannot happen anywhere. Annotate the boundaries first: public functions, data models and anything that crosses a module line. Inside a small function, the checker infers types well on its own.

checkout.py
def apply_discount(price: float, percent: int) -> float:
    return price * (1 - percent / 100)


apply_discount("100", 10)                  # wrong type for price
result: int = apply_discount(100.0, 10)    # the function returns a float, not an int
Running mypy checkout.py reports both mistakes without executing anything:
checkout.py:5: error: Argument 1 to "apply_discount" has incompatible type "str"; expected "float" [arg-type]
checkout.py:6: error: Incompatible types in assignment (expression has type "float", variable has type "int") [assignment]
Found 2 errors in 1 file (checked 1 source file)

Pydantic: validation at the edge

Hints do not stop bad data arriving from a web form, a JSON file or an environment variable, because that data appears at run time. Pydantic is a third-party library (pip install pydantic) that turns annotated classes into validators: it checks and converts incoming data, and raises a detailed error when it cannot. Many modern frameworks, FastAPI among them, are built on it. A good split is: plain dataclasses for trusted data inside your program, Pydantic models where data enters from outside. The output below was recorded with Pydantic 2.x.

validate_user.py
from pydantic import BaseModel, ValidationError


class User(BaseModel):
    name: str
    age: int


user = User(name="Asha", age="21")           # the string "21" is converted to the integer 21
print(user, type(user.age).__name__)

try:
    User(name="Ravi", age="old")             # cannot be converted: validation fails
except ValidationError as err:
    print(err.errors()[0]["msg"])
Pydantic is installed separately, so this output is a recorded run rather than something this page can generate. The model both documents the shape of a User and enforces it at the moment data arrives.

Remember this

  • Type hints are labels for humans and tools. Python stores them but does not enforce them at run time.
  • Use TypeVar and Generic so one function or class works for many types while keeping input and output linked.
  • Protocol describes the shape an object must have, and TypedDict describes the keys of a dict, with no inheritance needed.
  • Dataclasses remove boilerplate (frozen, slots, order, default_factory, __post_init__); Enums replace magic strings with named members.
  • Run a checker such as mypy in CI, start by annotating public boundaries, and avoid Any.
  • Validate untrusted data at the edge with a library like Pydantic; use plain dataclasses inside.

Your turn

Model a support-ticket system. Create an IntEnum called Priority with LOW=1, MEDIUM=2, HIGH=3. Create a dataclass Ticket with title: str, priority: Priority = Priority.LOW and tags: list[str] (a fresh empty list by default). In __post_init__, raise ValueError("title must not be empty") if the title is blank. Build three tickets, print them sorted from highest to lowest priority as HIGH Fix login, and show that a blank title is rejected.

Use <code>from enum import IntEnum</code>, <code>field(default_factory=list)</code> for the tags, and <code>sorted(tickets, key=lambda t: t.priority, reverse=True)</code>. <code>t.priority.name</code> gives the member name such as <code>HIGH</code>.

solution.py
from dataclasses import dataclass, field
from enum import IntEnum


class Priority(IntEnum):
    LOW = 1
    MEDIUM = 2
    HIGH = 3


@dataclass
class Ticket:
    title: str
    priority: Priority = Priority.LOW
    tags: list[str] = field(default_factory=list)

    def __post_init__(self) -> None:
        if not self.title.strip():
            raise ValueError("title must not be empty")


tickets = [
    Ticket("Fix login", Priority.HIGH, ["auth"]),
    Ticket("Update docs"),
    Ticket("Speed up search", Priority.MEDIUM),
]
for t in sorted(tickets, key=lambda t: t.priority, reverse=True):
    print(t.priority.name, t.title)

try:
    Ticket("   ")
except ValueError as err:
    print("rejected:", err)

Check yourself

What does Python do at run time if you call a function annotated (x: int) with a string?

How does a class satisfy a typing.Protocol?

Why does a dataclass reject the field items: list[Item] = [] ?

Ask the CipherCode AI tutor

Act as my Python tutor. Take a small program I describe (for example an order system with dictionaries) and show me how to add type hints, replace magic strings with an Enum, and replace dicts with dataclasses. Then explain what mypy would catch that tests would miss, and ask me one question to check I understood.

Next module

Module 7

Performance and profiling

Learn to measure before you optimise, find the real bottleneck with timeit and cProfile, and pick data structures, caching and memory techniques that make Python code fast for the right reasons.

About 60 minutes

Most slow Python programs are slow in one or two places, and those places are almost never where the author guessed. A developer who spends a day rewriting a loop that takes 2% of the run time has made the code harder to read and the program no faster. Performance work is therefore a loop of its own: measure, find the bottleneck, change one thing, measure again. This module gives you the tools for each step and the knowledge to choose the change that actually helps.

Step 1: time small pieces with timeit

The timeit module runs a snippet many times and reports the total seconds. It turns off garbage collection during the run and uses the best available clock, which removes much of the noise you get from wrapping code in time.time() calls. Use it to compare two small alternatives. Take the minimum of several repeats rather than the average, because slowdowns come from other programs on your machine, never from your code running unusually fast.

The example below shows the shape of a measurement. It deliberately prints no timings, because timings differ on every computer. It prints facts about the result instead. When you run it yourself, print min(times) and compare the two numbers.

timeit_demo.py
import timeit

setup = "prices = list(range(1000))"

# Two ways to build the same list of discounted prices.
loop_version = """
result = []
for p in prices:
    result.append(p * 9 // 10)
"""
comp_version = "result = [p * 9 // 10 for p in prices]"

# repeat() runs the whole measurement several times; number= is runs per repeat.
loop_times = timeit.repeat(loop_version, setup=setup, repeat=3, number=200)
comp_times = timeit.repeat(comp_version, setup=setup, repeat=3, number=200)

print(len(loop_times), len(comp_times))        # 3 measurements each
print(min(loop_times) > 0, min(comp_times) > 0)

# On your machine, compare min(loop_times) with min(comp_times).
# The comprehension is usually a little faster because it avoids the
# repeated method lookup of result.append, but only the measurement
# on YOUR data and YOUR Python version can tell you for sure.
setup runs once per repeat and is not timed. number=200 means each repeat executes the snippet 200 times. Always compare the minimum of the repeats.

Step 2: find the bottleneck with cProfile

timeit answers “which of these two is faster?” but not “where does my program spend its time?”. For that you use a profiler. cProfile ships with Python. It records every function call, how many times it happened (ncalls), the time spent inside the function itself (tottime), and the time including everything it called (cumtime).

Run it on a whole script with python -m cProfile -s cumtime app.py, or around a block of code with cProfile.Profile() and pstats.Stats. Read the output top-down by cumtime to find which of your functions owns the time, then look at tottime inside it to see whether the cost is the function's own work or something it calls. The output below shows the shape for a small log-analysis script. Exact numbers will differ on your machine.

profile_logs.py
import cProfile
import pstats


def parse_line(line):
    ip, status = line.split(",")
    return ip, int(status)


def count_errors(lines):
    errors = 0
    for line in lines:
        ip, status = parse_line(line)
        if status >= 500:
            errors += 1
    return errors


lines = [f"10.0.0.{i % 255},{200 + (i % 4) * 100}" for i in range(200_000)]

profiler = cProfile.Profile()
profiler.enable()
count_errors(lines)
profiler.disable()

stats = pstats.Stats(profiler).sort_stats("cumulative")
stats.print_stats(4)                      # top 4 rows only
Walkthrough: count_errors owns almost all the cumulative time. Inside it, parse_line was called 200,000 times, which is a hint that per-line function-call overhead matters. The numbers shown are illustrative, so run it yourself to see your own.

Step 3: choose the right data structure

The biggest speed-ups usually come from choosing a better algorithm, not from clever tricks. Computer scientists describe growth with Big-O notation: O(1) means the cost stays flat as the data grows, O(n) means it grows in step with the data, and O(n^2) means doubling the data quadruples the work. Testing x in some_list is O(n) because Python may check every element, while x in some_set and key in some_dict are O(1) on average because they use hashing.

You needUseCost
Fast membership testset or dictO(1) average
Add or remove at both endscollections.dequeO(1) at each end; list is O(n) at the front
Keep a list sorted and search itbisect on a sorted listO(log n) search
Always get the smallest item nextheapqO(log n) push and pop
Count itemscollections.CounterO(1) per item
structures.py
import bisect
import heapq
from collections import deque

# 1. Membership: a set answers "have I seen this?" without scanning.
seen_ids = set()
for order_id in [101, 205, 101, 307, 205]:
    if order_id in seen_ids:
        print("duplicate:", order_id)
    seen_ids.add(order_id)

# 2. deque: a queue that is cheap at BOTH ends.
queue = deque(["amit", "priya", "rahul"])
queue.append("sneha")            # join the back
print(queue.popleft())           # serve the front in O(1); list.pop(0) is O(n)

# 3. bisect: binary search inside a sorted list.
marks = [35, 48, 62, 71, 85, 93]
position = bisect.bisect_left(marks, 70)
print("first mark >= 70 is at index", position, "->", marks[position])
bisect.insort(marks, 66)         # insert and keep the list sorted
print(marks)

# 4. heapq: always the smallest pending job first (a priority queue).
jobs = []
heapq.heappush(jobs, (3, "send report"))
heapq.heappush(jobs, (1, "restart server"))
heapq.heappush(jobs, (2, "clear cache"))
while jobs:
    priority, name = heapq.heappop(jobs)
    print(priority, name)
Each structure exists because one operation on a plain list is slow. Pick the structure whose fast operation matches what your loop does most.

Step 4: save memory and repeated work

Speed and memory are linked, because creating huge objects takes time too. A generator expression produces values one at a time instead of building a full list, so it uses almost constant memory. __slots__ tells a class not to create a per-instance __dict__, which saves memory when you create hundreds of thousands of small objects. functools.lru_cache stores the results of a pure function so repeated calls with the same arguments cost nothing. And building a large string with repeated += in a loop may copy the growing text each time, so collect pieces in a list and call ''.join(pieces) once.

memory_tools.py
import sys
import tracemalloc
from functools import lru_cache


# --- generator vs list: peak memory --------------------------------
def peak_bytes(make_total):
    tracemalloc.start()
    make_total()
    _, peak = tracemalloc.get_traced_memory()
    tracemalloc.stop()
    return peak

list_peak = peak_bytes(lambda: sum([n * n for n in range(100_000)]))
gen_peak = peak_bytes(lambda: sum(n * n for n in range(100_000)))
print("generator peak is far smaller:", gen_peak * 10 < list_peak)


# --- __slots__: no per-instance dictionary --------------------------
class PlainPoint:
    def __init__(self, x, y):
        self.x, self.y = x, y

class SlotPoint:
    __slots__ = ("x", "y")
    def __init__(self, x, y):
        self.x, self.y = x, y

print(hasattr(PlainPoint(1, 2), "__dict__"), hasattr(SlotPoint(1, 2), "__dict__"))


# --- lru_cache: remember results of a pure function -----------------
@lru_cache(maxsize=None)
def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)

print(fib(80))                  # instant; the plain version would take ages
print(fib.cache_info().currsize)


# --- joining strings ------------------------------------------------
pieces = [f"row{i}" for i in range(5)]
print(",".join(pieces))
tracemalloc reports the peak bytes allocated while the block ran. We compare the two peaks instead of printing them, because exact byte counts depend on the Python version.

Step 5: when pure Python is not enough

Sometimes the algorithm is right and the loop is still too slow, because CPython executes one bytecode instruction at a time. The cure is to move the hot loop out of Python. NumPy stores numbers in a compact array and runs the loop in compiled C, so an operation on a million numbers is a single call. numba compiles numeric Python functions to machine code with one decorator. Cython and Rust (through PyO3 and maturin) let you write the hot function in a compiled language and call it from Python. Reach for these last, only for a function the profiler has proven to be the bottleneck, because each one adds a build step and a second language to your project.

numpy_vectorise.py
import numpy as np

prices = np.array([120.0, 80.0, 250.0, 40.0])
quantities = np.array([3, 10, 1, 25])

# Pure Python would need a loop; NumPy applies the maths to every element at once.
totals = prices * quantities
print(totals)
print(totals.sum())

# Boolean masks replace "if" inside a loop.
print(prices[prices > 100])
NumPy is a third-party package (pip install numpy), so this output is shown rather than generated here. The idea is called vectorisation: write the operation on whole arrays and let compiled code do the looping.

Remember this

  • Measure first: use timeit to compare small alternatives and cProfile to find where the program really spends its time.
  • Better algorithms and data structures beat tricks: sets and dicts for membership, deque for queues, bisect for sorted search, heapq for priorities.
  • Generators, __slots__, lru_cache and ''.join each save memory or repeated work in specific, well-understood situations.
  • Profilers add overhead, so confirm any gain with an ordinary timing and realistic data.
  • Move to NumPy, numba, Cython or Rust only for a proven hot spot, because each adds complexity.

Your turn

A script checks 20,000 order IDs against a list of 20,000 blocked IDs with if order in blocked_list. Rewrite it so the membership test is fast. Build blocked = {...} once, then count how many of the orders range(0, 40_000, 2) are blocked when the blocked IDs are range(0, 60_000, 3). Print the count.

Convert the blocked IDs to a <code>set</code> once before the loop, and then use <code>sum(1 for ... if order in blocked)</code> or a simple counter.

solution.py
blocked = set(range(0, 60_000, 3))          # built ONCE: O(n)
orders = range(0, 40_000, 2)

# Each "in" test on a set is O(1) on average instead of scanning a list.
blocked_count = sum(1 for order in orders if order in blocked)
print(blocked_count)

Check yourself

You think a function is slow. What should you do first?

Why is `x in some_set` faster than `x in some_list` for large collections?

What is the main trade-off of using __slots__ on a class?

Ask the CipherCode AI tutor

Act as my Python performance coach. Give me a deliberately slow 30-line script, then walk me through profiling it with cProfile and fixing the top bottleneck with a better data structure. Ask me to predict the result before each measurement, and explain where my intuition was wrong.

Next module

Module 8

Descriptors and metaclasses

Learn the hooks Python uses to look up, set and create attributes and classes, so that properties, methods, dataclasses and ORMs stop feeling like magic.

About 60 minutes

Every time you write obj.name Python runs a small, well-defined procedure. Most of the time you never think about it. But @property, methods, @classmethod, __slots__, dataclass fields and every ORM column are all built from the same few hooks, collectively called the data model. This module opens that box. By the end you will know how to write your own validated attribute, intercept missing attributes, shrink objects, react when a subclass is created, and decide when a metaclass is truly necessary (rarely).

Descriptors: attributes that run code

A descriptor is an object, stored as a class attribute, that defines at least one of __get__, __set__ or __delete__. When you access an attribute and Python finds a descriptor on the class, it calls the descriptor instead of returning it as plain data. Think of the class attribute as a receptionist: you ask for a value at the desk, and the receptionist decides what to hand over, or whether to refuse your update.

The three methods have fixed signatures. __get__(self, obj, objtype) runs on read. obj is the instance, or None when the attribute is read from the class itself. __set__(self, obj, value) runs on assignment. __set_name__(self, owner, name) is an optional extra that Python calls once when the class is built, telling the descriptor what name it was given. That saves you from typing the attribute name twice.

validated_attribute.py
class Positive:
    """A descriptor that only accepts numbers above zero."""

    def __set_name__(self, owner, name):
        # Called once, when the class body finishes: name is 'price' or 'seats'.
        self.storage = "_" + name

    def __get__(self, obj, objtype=None):
        if obj is None:
            return self                      # accessed on the class: return the descriptor
        return getattr(obj, self.storage)

    def __set__(self, obj, value):
        if value <= 0:
            raise ValueError(f"{self.storage[1:]} must be positive, got {value}")
        setattr(obj, self.storage, value)    # real data lives on the instance


class Ticket:
    price = Positive()
    seats = Positive()

    def __init__(self, price, seats):
        self.price = price                   # goes through Positive.__set__
        self.seats = seats


t = Ticket(250, 2)
print(t.price, t.seats)
try:
    Ticket(-5, 1)
except ValueError as e:
    print(e)
print(type(Ticket.__dict__["price"]).__name__)
print(Ticket.price is Ticket.__dict__["price"])
Ticket.price is declared once, but both price and seats reuse the same validation. One descriptor class replaces many repeated @property pairs.

Line-by-line: when the class Ticket is created, Python calls __set_name__ on each Positive it finds, passing 'price' and 'seats'. When __init__ runs self.price = price, Python sees that the class has a descriptor called price with a __set__, so it calls that instead of writing straight to the instance dictionary. The descriptor then stores the real value under _price. Notice that one descriptor object is shared by every Ticket, so it must never keep per-instance data on self. It stores the data on obj.

Lookup order: data versus non-data descriptors

A descriptor with __set__ or __delete__ is a data descriptor. One with only __get__ is a non-data descriptor. The difference decides who wins when the instance also has a value of the same name in its __dict__. Python checks in this order: data descriptors on the class, then the instance __dict__, then non-data descriptors and plain class attributes. Ordinary functions are non-data descriptors. That is exactly how methods work: Class.method.__get__(instance, Class) returns a bound method with self filled in.

lookup_order.py
class Loud:
    """Non-data descriptor: only __get__."""
    def __get__(self, obj, objtype=None):
        return "from non-data descriptor"


class Quiet:
    """Data descriptor: has __set__ too."""
    def __get__(self, obj, objtype=None):
        return "from data descriptor"

    def __set__(self, obj, value):
        print("set intercepted:", value)


class Demo:
    a = Loud()
    b = Quiet()


d = Demo()
d.__dict__["a"] = "instance value wins"
d.__dict__["b"] = "instance value loses"
print(d.a)
print(d.b)
d.b = 5
print(d.__dict__["b"])


class Greeter:
    def hello(self):
        return "hi"


g = Greeter()
bound = Greeter.__dict__["hello"].__get__(g, Greeter)   # what g.hello does
print(type(bound).__name__, bound())
@property is a ready-made data descriptor, which is why you cannot shadow a property by writing into instance.__dict__.

__getattr__ versus __getattribute__

These two names look alike and behave very differently. __getattribute__ runs on every attribute lookup. __getattr__ runs only as a fallback, after normal lookup has failed with AttributeError. Use __getattr__ for proxies, lazy attributes and configuration objects. Reach for __getattribute__ only for tracing or very unusual control, and always delegate to super().__getattribute__, otherwise you create infinite recursion.

dynamic_attributes.py
class Config:
    def __init__(self, data):
        self._data = data

    def __getattr__(self, name):
        # Only reached when normal lookup fails (e.g. cfg.host).
        try:
            return self._data[name]
        except KeyError:
            raise AttributeError(f"no setting called {name!r}") from None


class Tracer:
    def __init__(self):
        self.x = 1

    def __getattribute__(self, name):
        print("looking up", name)                     # runs for EVERY lookup
        return super().__getattribute__(name)


cfg = Config({"host": "localhost", "port": 8080})
print(cfg.host, cfg.port)
try:
    cfg.user
except AttributeError as e:
    print(e)

t = Tracer()
print(t.x)

__slots__: fixed attributes, smaller objects

Normally each instance carries a __dict__, a dictionary of its attributes. That is flexible and costs memory. Declaring __slots__ = ('x', 'y') replaces the dictionary with a fixed array of slots. Objects get smaller and attribute access slightly faster, which matters when you create millions of small objects. The price: you cannot add attributes that were not declared, and weak references and multiple inheritance get fiddlier.

slots_demo.py
class Plain:
    def __init__(self, x, y):
        self.x = x
        self.y = y


class Slim:
    __slots__ = ("x", "y")

    def __init__(self, x, y):
        self.x = x
        self.y = y


p, s = Plain(1, 2), Slim(1, 2)
print(hasattr(p, "__dict__"), hasattr(s, "__dict__"))
p.z = 3                                   # fine: the dictionary accepts anything
print(p.z)
try:
    s.z = 3                               # no slot called z, no dictionary to fall back on
except AttributeError as e:
    print(type(e).__name__)

__init_subclass__, ABCs and plugin registries

__init_subclass__ is a hook on a parent class that Python calls each time someone subclasses it. It covers most of what people used metaclasses for, in plain code. Pair it with an abstract base class (abc.ABC with @abstractmethod) and you get a plugin registry: subclasses register themselves just by being defined, and Python refuses to create objects from subclasses that forgot a required method.

plugin_registry.py
import json
from abc import ABC, abstractmethod


class Exporter(ABC):
    registry = {}

    def __init_subclass__(cls, fmt=None, **kwargs):
        super().__init_subclass__(**kwargs)
        if fmt:                                    # runs once per subclass definition
            Exporter.registry[fmt] = cls

    @abstractmethod
    def export(self, rows):
        """Turn rows into a string."""


class CsvExporter(Exporter, fmt="csv"):
    def export(self, rows):
        return "\n".join(",".join(map(str, r)) for r in rows)


class JsonExporter(Exporter, fmt="json"):
    def export(self, rows):
        return json.dumps(rows)


class Broken(Exporter, fmt="broken"):
    pass                                           # forgot export()


rows = [[1, "a"], [2, "b"]]
print(sorted(Exporter.registry))
print(Exporter.registry["csv"]().export(rows))
print(Exporter.registry["json"]().export(rows))
try:
    Exporter.registry["broken"]()
except TypeError as e:
    print("TypeError:", e)

Metaclasses: classes that make classes

Classes are objects too, and something has to create them. By default that something is type. A metaclass is a subclass of type that you plug in with class Thing(metaclass=Meta). Its __new__ runs when the class body is finished, with the class name, its bases and the namespace dictionary, so it can inspect or rewrite the class before it exists. Frameworks such as Django models and SQLAlchemy use this to collect field declarations.

metaclass_demo.py
class DocRequired(type):
    def __new__(mcls, name, bases, namespace):
        for attr, value in namespace.items():
            if callable(value) and not attr.startswith("_") and not value.__doc__:
                raise TypeError(f"{name}.{attr} needs a docstring")
        return super().__new__(mcls, name, bases, namespace)


class Service(metaclass=DocRequired):
    def start(self):
        """Start the service."""
        return "started"


print(type(Service).__name__, type(Service) is DocRequired, Service().start())

try:
    class Bad(metaclass=DocRequired):
        def stop(self):
            return "stopped"
except TypeError as e:
    print(e)

print(type(Service) is type, type(int).__name__)

Remember this

  • A descriptor is a class attribute with __get__, __set__ or __delete__, and one instance is shared by every object, so store data on the instance.
  • Data descriptors beat the instance dictionary, which beats non-data descriptors. Functions and properties are descriptors, which is how methods get self.
  • __getattr__ is a fallback for missing names. __getattribute__ runs on every lookup and must call super() to avoid recursion.
  • __slots__ trades flexibility for smaller, faster objects: no per-instance dictionary and no new attributes.
  • __init_subclass__ plus an ABC gives you plugin registries and early errors without a metaclass. Use a metaclass only when nothing simpler works.

Your turn

Write a descriptor Between(low, high) that rejects values outside the range with a ValueError whose message names the attribute. Use it for a Thermostat.target between 10 and 30. Create Thermostat(22), print its target, then try to set the target to 50 and print the error message.

Take low and high in __init__. Use __set_name__ to learn the attribute name, store the value on obj under a private name, and compare with low <= value <= high.

solution.py
class Between:
    def __init__(self, low, high):
        self.low = low
        self.high = high

    def __set_name__(self, owner, name):
        self.name = name
        self.storage = "_" + name

    def __get__(self, obj, objtype=None):
        if obj is None:
            return self
        return getattr(obj, self.storage)

    def __set__(self, obj, value):
        if not (self.low <= value <= self.high):
            raise ValueError(f"{self.name} must be between {self.low} and {self.high}, got {value}")
        setattr(obj, self.storage, value)


class Thermostat:
    target = Between(10, 30)

    def __init__(self, target):
        self.target = target


t = Thermostat(22)
print(t.target)
try:
    t.target = 50
except ValueError as e:
    print(e)

Check yourself

Why must a descriptor store per-object data on the instance (obj) rather than on self?

When does __getattr__ run?

Which tool is the best first choice for registering every subclass of a base class automatically?

Ask the CipherCode AI tutor

Act as a Python tutor. Explain the descriptor protocol with a Positive-number example, then show how @property and normal methods are descriptors underneath. Quiz me on data versus non-data descriptor lookup order with three short code snippets and ask me to predict the output of each.

Next module

Module 9

Packaging, APIs and production

Turn your code into something other people can install, call over HTTP, configure safely, observe in production and review with confidence.

About 65 minutes

Writing correct code is half of the job. The other half is getting it to run somewhere else, for someone else, and staying understandable when it breaks at 3 a.m. This final module covers the habits that separate a script from a service: packaging, a web API, configuration, logging, containers, automated checks, a few design patterns and a code review checklist. None of it is exotic. All of it is expected of a professional Python developer.

Packaging with pyproject.toml

A package is code with a name, a version and declared dependencies, so anyone can run pip install on it. The modern standard is one file, pyproject.toml, which replaces the old setup.py and requirements.txt combination. It holds three things: the build system (which tool turns your folder into an installable file), the project metadata (name, version, Python version, dependencies) and optional tool settings. The recommended layout puts your code in src/yourpackage/, so tests always run against the installed copy and not the loose folder.

pyproject.toml
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[project]
name = "salon-booking"
version = "1.0.0"
description = "Booking API for small salons"
requires-python = ">=3.10"
dependencies = [
    "fastapi>=0.110",
    "uvicorn>=0.29",
]

[project.optional-dependencies]
dev = ["pytest>=8", "ruff>=0.4", "mypy>=1.10"]

[project.scripts]
salon = "salon_booking.cli:main"      # creates a 'salon' command on install
Build installable files with python -m pip install build then python -m build. That creates a wheel (.whl, a ready-to-install archive) and an sdist (.tar.gz, the source) in dist/. Try them with pip install dist/salon_booking-1.0.0-py3-none-any.whl inside a fresh virtual environment. Publish with twine upload dist/*.

A minimal API with FastAPI

An API lets other programs use your code over HTTP. FastAPI is a popular framework built on type hints: you describe the shape of a request with a pydantic model and FastAPI validates input, converts types, returns correct status codes and writes interactive documentation for free at /docs. A handler is just a function decorated with the HTTP method and path. Read the example below as three questions: what comes in (Booking), what goes out (a dictionary), and what can go wrong (a 404).

main.py
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

app = FastAPI(title="Salon booking API", version="1.0.0")


class Booking(BaseModel):
    name: str
    seats: int


BOOKINGS: dict[int, Booking] = {}          # a dictionary stands in for a database


@app.get("/health")
def health():
    return {"status": "ok"}


@app.post("/bookings", status_code=201)
def create_booking(booking: Booking):      # invalid JSON is rejected automatically (422)
    new_id = len(BOOKINGS) + 1
    BOOKINGS[new_id] = booking
    return {"id": new_id, **booking.model_dump()}


@app.get("/bookings/{booking_id}")
def read_booking(booking_id: int):
    if booking_id not in BOOKINGS:
        raise HTTPException(status_code=404, detail="Booking not found")
    return BOOKINGS[booking_id]
Install with pip install fastapi uvicorn and start it with uvicorn main:app --reload. In a second terminal: curl localhost:8000/health prints {"status":"ok"}. curl -X POST localhost:8000/bookings -H 'Content-Type: application/json' -d '{"name":"Asha","seats":2}' prints {"id":1,"name":"Asha","seats":2}. Asking for /bookings/99 returns {"detail":"Booking not found"} with status 404. Open http://localhost:8000/docs to try every route in your browser.

Configuration from the environment

The twelve-factor approach says: configuration that changes between environments belongs in environment variables, not in code. The same build then runs on your laptop, in testing and in production, and secrets such as database passwords never enter your repository. Read them once at startup into a frozen object, convert types there (an environment variable is always a string) and give safe defaults only for non-secret values.

settings.py
import os
from dataclasses import dataclass


@dataclass(frozen=True)
class Settings:
    env: str
    port: int
    debug: bool
    database_url: str

    @classmethod
    def from_env(cls):
        return cls(
            env=os.environ.get("APP_ENV", "development"),
            port=int(os.environ.get("APP_PORT", "8000")),          # str -> int
            debug=os.environ.get("APP_DEBUG", "0") == "1",         # str -> bool
            database_url=os.environ.get("DATABASE_URL", "sqlite:///dev.db"),
        )


for key in ("APP_ENV", "APP_PORT", "APP_DEBUG", "DATABASE_URL"):
    os.environ.pop(key, None)                                      # start from a clean slate
print(Settings.from_env())

os.environ["APP_ENV"] = "production"                               # what a server would set
os.environ["APP_PORT"] = "9000"
os.environ["DATABASE_URL"] = "postgresql://db.internal/salon"
print(Settings.from_env())

Structured logging

print is for you at your desk. Production needs logging: severity levels, a source name and machine-readable output that a log service can search. The best practice is one JSON object per line, with fixed field names and extra context such as a booking id. Then you can ask a tool, "show every ERROR for booking 7", instead of reading text with your eyes. The standard library already does this: write a Formatter that returns JSON and attach it to a handler.

json_logging.py
import json
import logging
import sys


class JsonFormatter(logging.Formatter):
    def format(self, record):
        payload = {
            "level": record.levelname,
            "logger": record.name,
            "message": record.getMessage(),
        }
        payload.update(getattr(record, "ctx", {}))          # extra context fields
        if record.exc_info:
            payload["error"] = self.formatException(record.exc_info).splitlines()[-1]
        return json.dumps(payload, sort_keys=True)


handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(JsonFormatter())
log = logging.getLogger("salon.booking")
log.addHandler(handler)
log.setLevel(logging.INFO)
log.propagate = False

log.debug("this is hidden because the level is INFO")
log.info("booking created", extra={"ctx": {"booking_id": 7, "seats": 2}})
log.warning("slot almost full", extra={"ctx": {"remaining": 1}})
try:
    1 / 0
except ZeroDivisionError:
    log.exception("payment failed")                          # includes the error line

Containers and automated checks

A Docker image bundles your code, Python and system libraries into one unit that runs identically everywhere. Order the Dockerfile so that things that change rarely come first: Docker caches each step, so copying pyproject.toml and installing dependencies before copying your source means a code edit does not reinstall everything. Continuous integration (CI) runs your checks on every push so mistakes are caught before a human reviews them. A typical pipeline lints, type checks, runs tests and builds the image.

Dockerfile
FROM python:3.12-slim
WORKDIR /app

# Dependencies first: this layer is cached until pyproject.toml changes.
COPY pyproject.toml ./
RUN pip install --no-cache-dir .

COPY src ./src
RUN useradd --create-home appuser      # never run as root
USER appuser

ENV APP_ENV=production
EXPOSE 8000
CMD ["uvicorn", "salon_booking.main:app", "--host", "0.0.0.0", "--port", "8000"]
Build with docker build -t salon-booking . and run with docker run -p 8000:8000 -e DATABASE_URL=... salon-booking. Note how the secret arrives through -e at runtime and is not baked into the image.
ci.yml
name: ci
on: [push, pull_request]

jobs:
  checks:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        python-version: ["3.10", "3.12"]   # test every version you support
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: ${{ matrix.python-version }}
      - run: pip install -e ".[dev]"
      - run: ruff check .                  # lint
      - run: mypy src                      # types
      - run: pytest                        # tests
Save it as .github/workflows/ci.yml. GitHub runs it on every push and shows a green tick or red cross beside each commit.

Design patterns, the Python way

Many classic patterns from other languages shrink in Python because functions are objects, modules are singletons and duck typing removes the need for interface hierarchies. Learn the problem each pattern solves, then use the lightest tool that solves it.

ProblemClassic patternUsual Python solution
Swap an algorithm at runtimeStrategyPass a function as an argument
One shared instanceSingletonA module-level object
Add behaviour around a callDecoratorA @decorator function
Create objects by nameFactoryA dictionary mapping names to classes or functions
React when something happensObserverA list of callbacks, or a signal library
Hide a messy subsystemFacadeOne small module exposing a clean function set
Guarantee cleanupRAIIA context manager (with)

A code review checklist

Use this list when you review a colleague's pull request, and run through it on your own work before asking for review.

  • Correct: Does it do what the ticket says, including empty input, huge input and failure paths?
  • Tested: Is there a test that would fail without this change? Do tests check behaviour, not implementation details?
  • Readable: Can you explain each function in one sentence? Are names honest? Are there comments for why, not what?
  • Typed and linted: Do ruff and mypy pass? Are public functions annotated?
  • Safe: No secrets in code, no string-built SQL, no unchecked user input, and resources closed with with.
  • Observable: Will a failure leave a useful log line with enough context to diagnose it?
  • Small: Is the change focused enough to review in one sitting? Split unrelated edits into separate pull requests.

Remember this

  • pyproject.toml declares build system, metadata and dependencies. Build a wheel with python -m build, and install it in a clean environment to test it.
  • FastAPI plus pydantic validates requests from type hints and documents the API at /docs. Keep real state in a database, not in module variables.
  • Read configuration from environment variables once at startup, convert types there, and keep secrets out of code and images.
  • Log one JSON object per line with a level, a logger name and context fields so tools can search them.
  • Automate checks in CI and review against a checklist: correct, tested, readable, typed, safe, observable and small.

Your turn

Extend the settings example: add a workers field read from APP_WORKERS (an integer, default 2) and make from_env raise a ValueError with a clear message if APP_PORT is not a number. Set APP_PORT to abc, call from_env() and print the error message.

Wrap int(os.environ.get(...)) in a small helper that catches ValueError and re-raises it with the variable name in the message.

solution.py
import os
from dataclasses import dataclass


def read_int(name, default):
    raw = os.environ.get(name, str(default))
    try:
        return int(raw)
    except ValueError:
        raise ValueError(f"{name} must be a whole number, got {raw!r}") from None


@dataclass(frozen=True)
class Settings:
    port: int
    workers: int

    @classmethod
    def from_env(cls):
        return cls(port=read_int("APP_PORT", 8000), workers=read_int("APP_WORKERS", 2))


os.environ.pop("APP_WORKERS", None)
os.environ["APP_PORT"] = "abc"
try:
    Settings.from_env()
except ValueError as e:
    print(e)

Check yourself

Why copy pyproject.toml and install dependencies before copying your source in a Dockerfile?

Where should a database password live in a twelve-factor application?

What does FastAPI do automatically when a request body does not match your pydantic model?

Ask the CipherCode AI tutor

Act as a senior Python engineer mentoring me. Review my project structure for packaging, configuration, logging and CI. Ask me five questions about my pyproject.toml, how I handle secrets, and how I would debug a failing request in production. Then give me a short checklist of what to fix first.

Build these to lock it in

Reading is not enough. Each project uses what you just learned, so build them without copying.

medium

Streaming log analyser

Process a multi-gigabyte log file in constant memory and report error rates per service, using only generators.

  • generators
  • yield from
  • collections.Counter
  • context managers
Build plan
  1. Write read_lines(path) as a generator wrapped in a context manager so the file always closes.
  2. Write parse(lines), filter_level(records, levels) and window(records, seconds) as separate generator stages.
  3. Chain the stages into one pipeline and aggregate with Counter at the very end.
  4. Prove it is lazy: run it on a 1 GB generated file and watch memory with tracemalloc.
  5. Add a --follow mode that keeps reading as new lines are appended (like tail -f).

hard

Concurrent link checker

Crawl a website and report every broken link, comparing a threaded version against an asyncio version.

  • asyncio
  • semaphores
  • timeouts
  • ThreadPoolExecutor
  • profiling
Build plan
  1. Build a thread-pool version with a bounded number of workers and a per-request timeout.
  2. Rebuild it with asyncio, using a Semaphore to limit concurrent connections.
  3. Add retries with exponential back-off using your own retry decorator.
  4. Measure both versions with the same site and write down which is faster and why.
  5. Write results as structured JSON logs and a summary table.

hard

Plugin-based export service

Ship a small, typed, tested FastAPI service whose export formats are plugins discovered automatically.

  • typing
  • __init_subclass__
  • FastAPI
  • pyproject.toml
  • CI
Build plan
  1. Define an Exporter base class that registers subclasses through __init_subclass__.
  2. Add CSV, JSON and Markdown exporters, each in its own module, fully type-hinted.
  3. Expose them through a FastAPI endpoint with validated request models.
  4. Package the project with pyproject.toml and a console script, and add a Dockerfile.
  5. Write a GitHub Actions workflow that runs ruff, mypy and pytest on three Python versions.

Quick reference

Keep this open while you code.

You writeIt means
iter(x) / next(it)Get an iterator, then pull one value; StopIteration means it is finished
(n * n for n in data)Generator expression: lazy, produces values on demand, uses almost no memory
yield from sub()Delegate to another generator and pass its values straight through
@functools.wraps(func)Copy name, docstring and metadata onto your decorator's wrapper
@lru_cache(maxsize=None)Memoise a pure function so repeated calls with the same arguments are free
with open(p) as f:Guarantee cleanup, even when an exception is raised inside the block
@contextmanagerTurn a generator with one yield into a context manager
ThreadPoolExecutorRun I/O-bound work (network, disk) concurrently on threads
ProcessPoolExecutorRun CPU-bound work in parallel on separate processes
await asyncio.gather(*coros)Run many coroutines concurrently and collect results in order
async with asyncio.TaskGroup() as tg:Structured concurrency: if one task fails, its siblings are cancelled
await asyncio.to_thread(fn, x)Run blocking code without freezing the event loop
def f(x: int | None) -> str:Type hints: documentation that mypy can check before you run anything
@dataclass(frozen=True, slots=True)Immutable, memory-light value objects with almost no boilerplate
python -m cProfile -s cumtime app.pyFind which functions actually consume the time
__init_subclass__(cls, **kw)Hook that runs when a class is subclassed; ideal for plugin registries

You have reached the top of this roadmap

Pick a direction (web, data and AI, automation, DevOps) and build something real.

See what comes next