▚ The Software Engineer's Field Manual
Chapter E19 · Primer + senior drill

Python Deep Dive — Internals + 150-Question Drill

"Python is easy to write and hard to explain. The senior round asks you to explain it."

150 questions · answers collapsed Every output on the page was produced by running the code Heavy on: object model · GIL and free-threading · asyncio · data model · typing

01 · Why this primer existsPython Is Simple to Write; the Bill Arrives in Production

Python hides a lot of machinery behind short, friendly lines. When that machinery misbehaves, the symptoms look like business bugs: the wrong discount, a feature that will not go faster. This chapter opens the machinery so you can explain both the symptom and the cause.

Meet pricer, a small Python service at a fictional food-delivery app called QuickBite (the same app that appears in the Cassandra and Python API chapters). Pricer takes an order, applies the tax rules, delivery fees and discount codes, and returns the total the customer will pay.

It is a good first service. It is about 900 lines, the team of four knows it well, and in the whole year before Black Friday it never paged anyone at night.

On Black Friday, two separate changes ship in the same week. Neither looks dangerous in code review. Both end up in the incident channel.

The first incident arrives at 18:10. A customer posts a screenshot: their cart shows a "FIRST50" discount that they never typed. Support finds nine more in ten minutes, then forty. All of them are people who ordered shortly after somebody who really did use a first-order code.

The cause is one line, written months earlier and copied from a tutorial. Here it is, with the real output from running it.

apply_codes_bug.py · Python 3.14runs offline
def apply_codes(order, codes=[]):
    if order.get("code"):
        codes.append(order["code"])
    return codes

print("customer A:", apply_codes({"id": "o-1", "code": "FIRST50"}))
print("customer B:", apply_codes({"id": "o-2"}))
print("defaults  :", apply_codes.__defaults__)
apply_codes_bug.py · output, Python 3.14runs offline
customer A: ['FIRST50']
customer B: ['FIRST50']
defaults  : (['FIRST50'],)

Customer B never asked for a code and got customer A's. The list that holds the codes was created once, when the def line ran, and every later call without an explicit list shares it. The last line of the output shows that list sitting inside apply_codes.__defaults__, a place most people did not know existed.

That is incident one: a bug about when Python creates objects. Section 02 takes it apart.

The second incident is slower and more expensive. Pricing 400,000 orders for a nightly report takes too long, and the pricing rules are pure arithmetic with no network calls. A developer reads that Python has threads and "parallelises" the work across four of them.

The report does not get faster. In one test it gets slower. Here is the incident on a faithful miniature: 400,000 orders priced by pure-Python rule arithmetic, split into four equal chunks, run with a pool of one thread and then four, best of three runs, on this chapter's machine (12 cores). The script is the one section 05 uses for the full benchmark.

gil_threads.py · Python 3.14runs offline
import sys, time
from concurrent.futures import ThreadPoolExecutor

ORDERS = 400_000

def price_rules(order_id):
    """CPU-bound stand-in for the pricing rules: pure Python arithmetic."""
    total = 0
    for k in range(25):
        total += (order_id * k) % 7 + (order_id ^ k) % 5
    return total

def price_chunk(bounds):
    lo, hi = bounds
    return sum(price_rules(i) for i in range(lo, hi))

def run(workers):
    step = ORDERS // 4                       # always 4 equal chunks; only the pool size changes
    chunks = [(i * step, (i + 1) * step) for i in range(4)]
    t0 = time.perf_counter()
    with ThreadPoolExecutor(workers) as pool:
        result = sum(pool.map(price_chunk, chunks))
    return time.perf_counter() - t0, result

gil = getattr(sys, "_is_gil_enabled", lambda: True)()
print(f"Python {sys.version.split()[0]}  GIL enabled: {gil}")
for workers in (1, 4):
    best = min(run(workers)[0] for _ in range(3))
    print(f"  {workers} thread(s): {best:6.2f} s for {ORDERS:,} orders (best of 3)")
gil_threads.py · output, Python 3.14.7 (normal build)runs offline
Python 3.14.7  GIL enabled: True
  1 thread(s):   0.70 s for 400,000 orders (best of 3)
  4 thread(s):   1.04 s for 400,000 orders (best of 3)

Four threads took 1.04 seconds where one thread took 0.70, so adding workers made the job about 49 percent slower. The size of that loss varies from run to run (a later re-run gave 1.71 s for four threads against 0.67 s for one), but the direction never changed: more threads, slower job. Now the identical file on the free-threaded build of Python 3.14, an alternative interpreter without the global lock.

gil_threads.py · output, Python 3.14.7t (free-threaded build)runs offline
Python 3.14.7  GIL enabled: False
  1 thread(s):   0.84 s for 400,000 orders (best of 3)
  4 thread(s):   0.25 s for 400,000 orders (best of 3)

Here four threads took 0.25 seconds against 0.84 for one, about 3.4 times faster. Same code, same machine, opposite result. Two things are visible in these numbers.

First, on the normal interpreter only one thread can run Python bytecode at a time, so extra threads add switching cost and no speed. Second, the free-threaded build pays for its freedom: its single-thread run (0.84 s) was slower than the normal build's (0.70 s). Measured separately with best-of-5 runs, the overhead on this pricer workload is about 23 percent (0.678 s against 0.832 s).

That overhead depends on the workload. On a much tighter loop that does nothing but integer arithmetic, I measured about 40 to 48 percent in two runs (0.81 s and 0.85 s on the normal build, 1.20 s and 1.19 s on the free-threaded one for four batches on one thread), so never quote one number. The full benchmark and its method are in section 05.

A note on numbers: the story numbers in the incidents (how many customers, which minute) are illustrative. Every block of program output on this page, including the timings, was produced by running the script shown above it on the course machine. Your timings will differ; the shape of the result will not.

Two incidents, two lines of code, one codebase. Both come from not knowing what happens underneath the line. That is what a senior Python interview probes: not whether you can write a decorator, but whether you can say what the interpreter does when the decorator runs.

What runs under one line

Take the smallest line pricer has, total = price * qty. It looks like one step. It is at least six, each handled by a different part of Python. The figure names them, and each one points to the section that teaches it.

What runs under one line: total = price * qty 1 Name lookup: LOAD_FAST price, LOAD_FAST qty taught in 02 and 04 2 Objects: two int objects, each with a reference count taught in 02 3 Data model: type(price).__mul__(price, qty) taught in 03 4 Bytecode: BINARY_OP 5 (*), the same for every type taught in 05 5 After warm-up: BINARY_OP_MULTIPLY_INT (int * int only) taught in 05 6 Result: a new int object (360), bound to the name total taught in 02
Fig. 19.1 — Six layers hide under one line of Python. Each layer is a section of this chapter; an incident can start in any of them.

You can watch layers 4 and 5 happen. This script uses dis, the standard module that prints the bytecode of a function. It prints the function once cold, calls it 2,000 times with ints, and prints it again with adaptive=True so the specialised form is visible.

dis_one_line.py · Python 3.14runs offline
import dis

def line_total(price, qty):
    total = price * qty
    return total

print("--- cold (first view)")
dis.dis(line_total)
for _ in range(2000):
    line_total(120, 3)
print("--- warm (after 2,000 calls with ints)")
dis.dis(line_total, adaptive=True)
dis_one_line.py · output, Python 3.14.7runs offline
--- cold (first view)
  3           RESUME                   0

  4           LOAD_FAST_BORROW_LOAD_FAST_BORROW 1 (price, qty)
              BINARY_OP                5 (*)
              STORE_FAST               2 (total)

  5           LOAD_FAST_BORROW         2 (total)
              RETURN_VALUE
--- warm (after 2,000 calls with ints)
  3           RESUME_CHECK             0

  4           LOAD_FAST_BORROW_LOAD_FAST_BORROW 1 (price, qty)
              BINARY_OP_MULTIPLY_INT   5 (*)
              STORE_FAST               2 (total)

  5           LOAD_FAST_BORROW         2 (total)
              RETURN_VALUE

The multiplication instruction started as BINARY_OP, which works for any two types. After 2,000 calls with ints, the interpreter replaced it in place with BINARY_OP_MULTIPLY_INT, a version that only handles int times int and skips the generic lookup. That rewriting is called specialisation, and it is a Python 3.11 feature explained in section 05.

The names of the load instructions (LOAD_FAST_BORROW_LOAD_FAST_BORROW) are specific to 3.14; older versions print a shorter name. The idea is the same in every version.

Do not memorise those instruction names. Memorise the shape: names, objects, the type's own methods, bytecode, speed-ups, a new object. When something goes wrong, you ask which layer it belongs to.

The six ideas

The whole primer reduces to six ideas. A senior candidate keeps all six in mind and can say, for any incident, which one it belongs to.

  1. Names and objects (section 02): a name is a label pointing at an object, not a box holding a value. Mutable default arguments, shared config copies, memory that is freed or leaked all follow from this.
  2. The data model (section 03): len(x), for, with, + and x.attr are all calls to special methods on the type. Learn those methods and operators, iteration, context managers and descriptors stop being magic.
  3. Functions are objects (section 04): functions carry attributes and captured variables, which is why closures, decorators and generators behave as they do.
  4. How CPython executes (section 05): source becomes bytecode, a loop runs it, a global lock protects it, and an import system loads modules exactly once. This is where the thread benchmark above is explained.
  5. Concurrency models (section 06): threads, processes, asyncio, subinterpreters and free-threaded threads each share different things and fail in different ways.
  6. Types, tools and performance (section 07): type hints that are not enforced, lock files, tests that patch the wrong name, and profiling before optimising.

Ideas one and two are the foundation. Almost every question in the first forty of the drill is one of them in disguise.

If you come from Java: ten habits that need adjusting

Many readers arrive from the Java chapters of this track. Java habits are good habits; they just point at the wrong thing in Python in ten specific places. Each row below names the habit, what Python really does, and the idiom block that fixes it.

Java habit → Python reality. Every row links to the idiom that teaches the fix.
Java habitPython realityIdiom
Primitives (int) are values; objects are references.Everything is an object. x = 5 makes a label point at an int object. Mutable defaults and shared lists come from this.None default
final makes a variable constant.Nothing stops rebinding. Immutability comes from the type (tuple, frozenset, frozen dataclass), not from the name.Frozen value
Override equals and hashCode together.Define __eq__ and Python sets __hash__ to None for you, so the class silently becomes unhashable.eq / hash contract
Interfaces are declared and implemented by name.Duck typing: any object with the right methods works. Protocol adds that idea to type checking.Protocol
Annotations are metadata that a framework reads.Decorators are code that runs at import time and replaces the function. Forget functools.wraps and names disappear.wraps decorator
Checked exceptions and try-with-resources.EAFP ("easier to ask forgiveness than permission"): try, catch, move on. with blocks do the cleanup.Context manager
Threads run in parallel on many cores.In the standard build, one lock lets one thread run Python bytecode at a time. CPU-bound work needs processes, or the free-threaded build.Process pool
Virtual threads: write blocking code, the runtime copes.asyncio needs async/await everywhere, and one blocking call stalls every task.to_thread
Maven and Gradle resolve and pin dependencies.A plain pip install does not pin transitive versions. A lock file (with uv, for example) does.Lock file
The JIT compiler is on by default and does the tuning.CPython is an interpreter that speeds up hot code by specialising bytecode. A JIT exists but is experimental. Measure before you tune.Profile first

The next block shows the convention this chapter uses whenever two worlds are compared. The left pane is the familiar way, labelled Java · Spring. The right pane is the Python way being taught, labelled Python. Under both is one sentence naming the shift in thinking.

The subject is a Money value object: an amount and a currency that compare by value and never change after creation. Java has a one-line answer since Java 16.

Java · Spring

A record declares the fields. The compiler writes the constructor, equals, hashCode and toString.

Money.javaruns offline
// illustrative
public record Money(
    BigDecimal amount,
    String currency) { }
// equals, hashCode, toString
// are generated, fields final

Python

A frozen dataclass does the same job. The decorator writes the methods, and frozen=True blocks assignment.

money_value.py (excerpt)runs offline
@dataclass(frozen=True)
class Money:
    amount: Decimal
    currency: str

The shift: Java builds immutability into the language keyword; Python builds it into a decorator that rewrites the class, and the type hints are not checked when the code runs.

Run it. The script creates two equal amounts and asks Python three questions about them.

money_value.py · Python 3.14runs offline
from dataclasses import dataclass
from decimal import Decimal

@dataclass(frozen=True)
class Money:
    amount: Decimal
    currency: str

a = Money(Decimal("10.00"), "INR")
b = Money(Decimal("10.00"), "INR")
print(a == b, a is b, hash(a) == hash(b))
print(a)
money_value.py · output, Python 3.14.7runs offline
True False True
Money(amount=Decimal('10.00'), currency='INR')

The two objects are equal (True), they are not the same object (False), and they hash alike (True). That is the contract Java programmers know from equals and hashCode. Section 03 shows how Python can break it by accident.

What changed from 3.11 to 3.15 (what interviewers ask)

Python releases a new minor version every October. A senior candidate is expected to know which releases changed behaviour that matters in production. This table lists one row per version. Facts were checked in November 2026; where a detail needs the official What's New page, the cell says so.

Python 3.11 to 3.15: the changes a senior interview asks about
VersionHeadline changesWhy it mattersTaught in
3.11 (Oct 2022)Specialising adaptive interpreter (PEP 659); zero-cost try; exception groups and except* (PEP 654); asyncio.TaskGroup and asyncio.timeout; tomllib.Documented as 10 to 60 percent faster than 3.10 (about 25 percent on average). Structured concurrency arrives.05, 06
3.12 (Oct 2023)Type-parameter syntax (PEP 695, def first[T](xs: list[T]), type aliases); f-string grammar (PEP 701); inlined comprehensions (PEP 709); itertools.batched; per-interpreter GIL in C (PEP 684).Cleaner generics and the groundwork for subinterpreters.04, 06, 07
3.13 (Oct 2024)Free-threaded build, experimental (PEP 703); experimental copy-and-patch JIT (PEP 744), off by default; new interactive REPL.First time the GIL can be turned off. Not for production yet.05
3.14 (Oct 2025)Free-threaded build officially supported (PEP 779) but still a separate build, python3.14t; template strings (PEP 750); deferred annotations (PEP 649/749); concurrent.interpreters and InterpreterPoolExecutor (PEP 734); compression.zstd; asyncio introspection (python -m asyncio ps). Default multiprocessing start method on Linux became forkserver (verified on the course machine).Three new ways to use many cores, and a changed default that breaks scripts without a main guard. The garbage-collector story changed during the 3.14 cycle: check the 3.14 What's New page before quoting anything.05, 06, 07
3.15 (Oct 2026)Explicit lazy imports (PEP 810, lazy import json); frozendict built-in (PEP 814); profiling package with the Tachyon sampling profiler (PEP 799); UTF-8 mode on by default (PEP 686); JIT improvements (reported gain of about 7 to 8 percent on x86-64 Linux; measure your own workload).Faster start-up, a built-in immutable mapping, a profiler you can attach to a running process, and fewer encoding bugs on Windows.02, 05, 07

Two caveats keep you honest in an interview. First, "officially supported" for the free-threaded build does not mean "the default". You install it separately and some C extension modules may switch the lock back on. Second, quoted speed-ups are averages on benchmark suites. Your service is not the benchmark.

How to read this chapter

The page has two halves. The primer (sections 02 to 07) teaches the six ideas in order. The drill (sections 08 to 11) is 150 interview questions, with every answer collapsed behind a Reveal answer control.

Each primer section follows one shape. It opens with a pricer incident that has real numbers in it, then shows the mechanism by running code, then offers one or more idioms, and ends with an interview sentence you can say aloud.

Mechanisms are explained twice: once in plain words, and once "one level down", under a heading that starts Bridge. The bridge shows what the interpreter actually does. If you only want the practical rule, you can read the plain explanation and the idiom, and skip the bridge on a first pass.

Every block of output was produced by running the script above it. The scripts live in the course's code/e19-python-deep-dive/ folder, so you can rerun them. Where this page shows an interpreter in the file name (Python 3.14, 3.14t, 3.15.0rc1), use the same one if you want the same output.

A block that starts with # illustrative was not run. It is a picture in code form, such as a Java snippet or a table of states.

Neighbours worth having open: Chapter E2 for the JVM memory model and garbage collectors (compared with CPython in section 02), Chapter E1 for the Java syntax that appears in the duos, the Python primer in the AI course if the language basics are not yet automatic, and Chapter E20 for building services with FastAPI, which uses everything here.

How every idiom in this chapter is laid out

A senior answer is rarely "use feature X". It is "here is the problem, here is the mechanism, here is the fix, here is where the fix breaks". Each idiom block has the same shape so you can scan for the part you need.

  1. The problem: what goes wrong without it, shown on pricer.
  2. How it works: the mechanism in two to four numbered steps.
  3. Without and with: a real run of the broken version, then a real run of the fixed version.
  4. Works / Fails: where the idiom helps and where it does not.
  5. Interview takeaway: the sentence to say aloud.

02 · Names, objects and memoryNames, Objects and Memory: What = Really Does

In Python a name is a label stuck on an object; it is never a box that holds a value. Almost every confusing behaviour in the first month of Python, and many production incidents after that, comes from forgetting it. This section follows labels, copies, reference counts and leaks one run at a time.

Pricer serves 40 tenants: restaurant chains, each with its own tax and fee settings. At start-up it loads a shared default configuration, and each tenant gets its own copy to adjust.

The code is short and looks careful. There is a base dictionary, and each tenant takes a .copy() of it before applying its overrides.

One Thursday a product manager adds a "surge" fee for tenant A, a pizza chain with a busy dinner rush. The developer appends it to tenant A's fee list. For the next three hours every one of the 40 tenants charges the surge fee on every order.

Nobody touched the other 39 tenants' settings, and no error was logged. The copy was never a copy of the part that mattered.

Section 02 explains exactly why, with a figure and a run. It also traces the codes=[] default from section 01 to the line of the interpreter that creates it, and it follows memory from the moment an object is born until the moment it is freed.

A name is a label, not a box

In many languages a variable is a box: the box has an address, and writing b = a copies the contents of one box into another. Python does not work that way. When Python runs a = [1, 2], it first builds a list object somewhere in memory, and then sticks a label called a on it.

Writing b = a builds nothing. It sticks a second label, b, on the same list. There is one list and two labels, and that is the whole story.

Three tools let you ask the question directly. id(x) returns a number that identifies the object a label points at. x is y asks whether two labels point at the very same object. x == y asks whether the objects they point at have equal contents.

names_and_ids.py · Python 3.14runs offline
a = [1, 2]
b = a              # a second label on the SAME list
b.append(3)
print("a =", a, " b =", b)
print("id(a) == id(b):", id(a) == id(b), " a is b:", a is b)

c = [1, 2, 3]      # a different list with equal contents
print("c == a:", c == a, " c is a:", c is a)

b = [9]            # rebinding: the label moves, the old list is untouched
print("after b = [9]: a =", a, " b =", b)
names_and_ids.py · output, Python 3.14.7runs offline
a = [1, 2, 3]  b = [1, 2, 3]
id(a) == id(b): True  a is b: True
c == a: True  c is a: False
after b = [9]: a = [1, 2, 3]  b = [9]
b = a; b.append(3) then b = [9] a b one list object [1, 2, 3] c another list [1, 2, 3] a is b True c == a True c is a False a b the old list [1, 2, 3] a new list [9] Rebinding moves a label. Mutating (append) changes the object every label on it can see.
Fig. 19.2 — A name is a label pointing at an object. b = a adds a second label to the same list, so append shows through both. b = [9] moves the label b and leaves the old list alone.

Read the output against the figure. After b.append(3), printing a shows [1, 2, 3] because there is only one list and append changed it. The list c has equal contents (c == a is True) but is a different object (c is a is False).

The last line is the one that surprises people. b = [9] does not change the old list at all. It builds a new list and moves the label b to it. Assignment moves labels; methods like append change objects. Keep those two verbs apart and half of Python's surprises disappear.

The is trap: why 257 behaves differently from 256

A famous interview question asks what x = 257; y = 257; x is y prints. The honest answer is "it depends on where you run it", and the next run shows three different places.

CPython keeps ready-made int objects for the numbers from -5 to 256, because small numbers are used constantly and building them over and over would waste time. Asking for 100 never builds a new int; it hands out the same prebuilt one each time. Numbers outside that range are built fresh whenever the program computes them.

is_trap.py · Python 3.14runs offline
# Way 1: one compiled unit (a file, or a function body): constants are shared
x = 257
y = 257
print("same compile unit  :", x is y)

# Way 2: separate compile units (what the interactive prompt does line by line)
ns = {}
exec("x = 257", ns)
exec("y = 257", ns)
print("separate exec calls:", ns["x"] is ns["y"])

# Way 3: values computed at run time
p = int("257")
q = int("257")
print("int('257') twice   :", p is q)

# Small-int cache: -5 .. 256 are pre-built
for text in ("256", "257", "-5", "-6"):
    print(f"int({text!r:6}) is int({text!r:6}):", int(text) is int(text))
is_trap.py · output, Python 3.14.7runs offline
same compile unit  : True
separate exec calls: False
int('257') twice   : False
int('256' ) is int('256' ): True
int('257' ) is int('257' ): False
int('-5'  ) is int('-5'  ): True
int('-6'  ) is int('-6'  ): False

The first line is True even though 257 is outside the cache. The reason is not the cache. When Python compiles one chunk of code (a file or a function), it stores each distinct constant once in the code object's constants table. Both x = 257 and y = 257 in the same chunk load the same stored object.

The second line compiles the two assignments separately, the way an interactive prompt does line by line. Now each chunk has its own 257, so the answer is False. The third line builds the numbers at run time with int("257"), so again False.

The loop at the end confirms the cache boundaries: 256 and -5 give True, 257 and -6 give False.

The lesson is not "memorise 256". The lesson is that is answers a question about object identity, and identity of numbers and strings is an implementation detail that can change between versions and between a file and a prompt. Use is only for singletons such as None, True and False, and for sentinel objects you made yourself. Use == for everything else.

Strings have a similar story called interning: the interpreter reuses one object for short, identifier-like strings. It is an optimisation, never a promise, so your code must not rely on it.

Mutable and immutable, and why dict keys must be hashable

An object is mutable if its contents can change after it is created, and immutable if they cannot. Lists, dicts and sets are mutable. Ints, floats, strings, tuples, bytes and frozensets are immutable. The new frozendict in Python 3.15 is an immutable dict.

The distinction decides what can be a dictionary key. A dict finds a key by computing its hash, a whole number derived from the contents, and using it to jump to a slot. If the contents of a key could change after insertion, its hash would change and the dict would look in the wrong slot and never find it again. So Python only allows keys whose hash can never change.

Tuples are the interesting case. A tuple is immutable, but it holds references, and a reference can point at a mutable object. The next run shows the rule and then a tuple that holds a list.

mutability.py · Python 3.14runs offline
import copy
t = ([1], 2)
try:
    t[0] += [3]
except TypeError as e:
    print("TypeError:", e)
print("t is now:", t)

for name, key in (("tuple of ints", (1, 2)), ("tuple holding a list", ([1], 2)), ("list", [1])):
    try:
        {key: "v"}
        print(f"{name:22} usable as dict key")
    except TypeError as e:
        print(f"{name:22} -> TypeError: {e}")
print("hash of (1, 2):", hash((1, 2)))
mutability.py · output, Python 3.14.7runs offline
TypeError: 'tuple' object does not support item assignment
t is now: ([1, 3], 2)
tuple of ints          usable as dict key
tuple holding a list   -> TypeError: cannot use 'tuple' as a dict key (unhashable type: 'list')
list                   -> TypeError: cannot use 'list' as a dict key (unhashable type: 'list')
hash of (1, 2): -3550055125485641917

Three things happen here. First, t[0] += [3] raises TypeError, and yet t afterwards contains [1, 3]. The reason is that += on a list first mutates the list in place (that part succeeds), and then tries to store the result back into slot 0 of the tuple (that part fails, because tuples cannot be assigned into). The error and the change both really happen.

Second, a tuple of ints is a valid key. Third, a tuple containing a list is not, because hashing a tuple hashes every element, and the list refuses. "Immutable container" does not mean "everything inside is frozen".

Python 3.15 adds frozendict as a built-in type. Here it is running on the 3.15.0rc1 interpreter. Note that it is a new name in the language itself, so no import is needed.

frozendict_315.py · Python 3.15.0rc1runs offline
fd = frozendict({"tax": "0.08", "fee": "2.00"})
print(type(fd), fd)
try:
    fd["tax"] = "0.18"
except TypeError as e:
    print("TypeError:", e)
print("hashable:", isinstance(hash(fd), int), " usable as key:", {fd: 1}[fd])
print("dict == frozendict:", {"tax": "0.08", "fee": "2.00"} == fd)
frozendict_315.py · output, Python 3.15.0rc1runs offline
<class 'frozendict'> frozendict({'tax': '0.08', 'fee': '2.00'})
TypeError: 'frozendict' object does not support item assignment
hashable: True  usable as key: 1
dict == frozendict: True

A frozendict refuses assignment, hashes, and can be a dict key. It compares equal to a plain dict with the same items. Compare it with the tools you had before. types.MappingProxyType gives a read-only view of a dict, but whoever holds the original dict can still change it. A frozen dataclass freezes the attributes of an object, not a key-value mapping. Only a frozendict is a genuinely immutable mapping.

Call by sharing

Is Python pass-by-value or pass-by-reference? Neither name fits. The accurate name is call by sharing: the function receives a new label pointing at the same object the caller passed.

That gives two different outcomes depending on what the function does with its label. If it mutates the object, the caller sees the change, because both labels point at one object. If it rebinds its own label, the caller sees nothing, because only the function's label moved.

call_by_sharing.py · Python 3.14runs offline
def add_one(xs):
    xs.append(1)      # mutates the object the caller also holds

def replace(xs):
    xs = [1]          # rebinds the local label only

mine = [0]
add_one(mine);  print("after add_one:", mine)
replace(mine);  print("after replace:", mine)
call_by_sharing.py · output, Python 3.14.7runs offline
after add_one: [0, 1]
after replace: [0, 1]

Java · Spring

Java passes the reference by value. The method gets a copy of the pointer, so the same two outcomes appear.

Cart.javaruns offline
// illustrative
void addOne(List<Integer> xs) {
  xs.add(1);       // caller sees it
}
void replace(List<Integer> xs) {
  xs = List.of(1); // caller does not
}

Python

Same model: a new label on the same object. The difference is only that every value is an object.

call_by_sharing.py (excerpt)runs offline
def add_one(xs):
    xs.append(1)   # caller sees it

def replace(xs):
    xs = [1]       # caller does not

The shift: the model is identical to Java's; what changes is that Java has primitives that are copied outright, while in Python even an int is an object behind a label.

Bridge: the mutable default argument, one level down

Now the first pricer incident can be explained. A def statement is not a declaration; it is a statement that runs. When Python executes it, Python builds a function object, evaluates every default expression right then, and stores the results in the function's __defaults__ tuple.

That happens once. Every later call that omits the argument reads the same stored object. For 0 or "abc" that is harmless, because those objects are immutable. For [] it is a trap, because the one stored list is changed by every call.

mutable_default.py · Python 3.14runs offline
def apply_codes(order, codes=[]):
    codes.append(order["code"])
    return codes

print("before any call:", apply_codes.__defaults__)
apply_codes({"code": "FIRST50"})
print("after call 1   :", apply_codes.__defaults__)
apply_codes({"code": "WELCOME"})
print("after call 2   :", apply_codes.__defaults__)
print("id of default list stays:", id(apply_codes.__defaults__[0]) == id(apply_codes.__defaults__[0]))
mutable_default.py · output, Python 3.14.7runs offline
before any call: ([],)
after call 1   : (['FIRST50'],)
after call 2   : (['FIRST50', 'WELCOME'],)
id of default list stays: True

Watch __defaults__ grow: it holds an empty list before any call, then one code, then two. The list is created exactly once, when the def line ran, and lives as long as the function does. Customer B's discount in section 01 was customer A's code, sitting in that tuple.

Idiom: the None default

The problem: a default argument of [], {} or set() is created once and shared by every call, so state leaks between callers.

How it works: use None as the default, which is immutable and therefore safe to share. Inside the function, create the real list when you see None.

  1. Declare: def apply_codes(order, codes=None). The only thing stored in __defaults__ is None.
  2. Check: if codes is None: codes = []. This line runs on every call, so each call builds its own list.
  3. When None is a real answer: make a private sentinel, _MISSING = object(), and compare with is. No caller can pass it by accident.

First, the version without the idiom, as already run in section 01:

without the idiom · apply_codes_bug.py, Python 3.14.7runs offline
customer A: ['FIRST50']
customer B: ['FIRST50']
defaults  : (['FIRST50'],)

Now with the idiom. The second function shows the sentinel for a parameter where None is a valid value.

none_default.py · Python 3.14runs offline
_MISSING = object()          # private sentinel: nobody else can pass it by accident

def apply_codes(order, codes=None):
    if codes is None:        # ✅ a fresh list on every call
        codes = []
    if order.get("code"):
        codes.append(order["code"])
    return codes

def set_discount(order, pct=_MISSING):
    if pct is _MISSING:
        return "pct not given"
    return f"pct given: {pct!r}"        # None is a legal value here

print("A:", apply_codes({"code": "FIRST50"}))
print("B:", apply_codes({}))
print(set_discount({}), "|", set_discount({}, None), "|", set_discount({}, 0))
print("defaults:", apply_codes.__defaults__)
with the idiom · none_default.py, Python 3.14.7runs offline
A: ['FIRST50']
B: []
pct not given | pct given: None | pct given: 0
defaults: (None,)

Customer B now gets an empty list. The last line shows __defaults__ holding only None. In the sentinel function, the three calls print three different messages, including None treated as a real value. A newer Python release may add a built-in sentinel type (PEP 661); check the current What's New before relying on it, and keep object() in the meantime.

Shallow and deep copies: the surge-fee incident

Return to the three-hour surge fee. The base config in pricer looked like this: a dict with a tax entry that is itself a dict, and a fees entry that is a list. Each tenant took base.copy().

A shallow copy builds a new outer container and fills it with the same inner objects. It copies one level. The new dict has its own slots, but each slot points at the same tax dict and the same fees list as the original. Appending to tenant_cfg["fees"] follows the label to the one shared list.

A deep copy follows every reference it can reach and copies those objects too, so afterwards the two structures share nothing.

shallow_deep.py · Python 3.14runs offline
import copy
base = {"tax": {"rate": "0.08"}, "fees": ["delivery"]}

shallow = base.copy()                 # new outer dict, SAME inner objects
shallow["fees"].append("surge")
print("base after shallow edit :", base["fees"])
print("inner shared?", shallow["fees"] is base["fees"], shallow["tax"] is base["tax"])

base = {"tax": {"rate": "0.08"}, "fees": ["delivery"]}
deep = copy.deepcopy(base)            # copies everything it can reach
deep["fees"].append("surge")
print("base after deep edit    :", base["fees"], " deep:", deep["fees"])
print("inner shared?", deep["fees"] is base["fees"])
print("dict(base) is also shallow:", dict(base)["fees"] is base["fees"])
shallow_deep.py · output, Python 3.14.7runs offline
base after shallow edit : ['delivery', 'surge']
inner shared? True True
base after deep edit    : ['delivery']  deep: ['delivery', 'surge']
inner shared? False
dict(base) is also shallow: True
Shallow copy: .copy() Deep copy: copy.deepcopy() base dict tenant copy tax dict fees list Two outer dicts, ONE inner list. Appending a fee through tenant_cfg changes base too. base dict tenant copy tax dict fees list tax dict (new) fees list (new) Every inner object is copied too, so the two configs no longer share anything.
Fig. 19.3 — Shallow versus deep copy of the pricer's tenant config. The shallow copy is a new outer dict whose values still point at the same inner dict and list; the deep copy duplicates every level.

The first two lines are the incident: the tenant's fee edit appears in base too, and both inner objects are the same (True True). The third and fourth lines show copy.deepcopy behaving as expected. The last line is a warning: dict(base), base.copy(), list.copy(), slicing xs[:] and copy.copy are all shallow.

Deep copies are not free. They walk the whole structure, so a config with thousands of nested items makes every tenant pay that cost. The idiom below says where to copy and when to avoid copying altogether.

Idiom: copy deliberately, or make it immutable

The problem: a shallow copy shares inner mutable objects, so a change meant for one owner shows up in all of them.

How it works: decide who owns each piece of mutable data, copy it once at the boundary where ownership changes, and where possible store data in types that cannot change.

  1. Find the boundary: the point where shared data becomes one tenant's data, here the function that builds a tenant's config.
  2. Copy there, deeply: copy.deepcopy(BASE) once per tenant, at start-up, not on every request.
  3. Prefer immutable inner values: a tuple of fees instead of a list means that even a shallow copy cannot be corrupted by an append.
  4. For a read-only shared object: wrap it in MappingProxyType, or in a frozendict on 3.15, and share it freely.
copy_deliberately.py · Python 3.14runs offline
import copy
from types import MappingProxyType

BASE = {"tax": {"rate": "0.08"}, "fees": ("delivery",)}

def tenant_config(overrides):
    cfg = copy.deepcopy(BASE)          # ✅ copy at the boundary
    cfg.update(overrides)
    return cfg

a = tenant_config({"fees": ("delivery", "surge")})
b = tenant_config({})
print("tenant A:", a["fees"], " tenant B:", b["fees"], " BASE:", BASE["fees"])

view = MappingProxyType(BASE)          # read-only window onto BASE
try:
    view["tax"] = {}
except TypeError as e:
    print("MappingProxyType:", e)
print("but inner objects can still change:", type(view["tax"]).__name__, "is a plain dict")
with the idiom · copy_deliberately.py, Python 3.14.7runs offline
tenant A: ('delivery', 'surge')  tenant B: ('delivery',)  BASE: ('delivery',)
MappingProxyType: 'mappingproxy' object does not support item assignment
but inner objects can still change: dict is a plain dict

Tenant A's fees now differ from tenant B's, and BASE never changed. The tuple of fees means an accidental .append would raise an error immediately instead of corrupting data quietly.

The last two lines are an honest warning about MappingProxyType: the view blocks assignment on the outer dict, but the inner tax value is still an ordinary mutable dict. A read-only wrapper is only as deep as it is built.

Bridge: how CPython frees memory, one level down

Every object in CPython carries a small hidden number, its reference count: how many labels (and other objects' slots) currently point at it. Assigning a name adds one. Deleting a name, rebinding it or leaving a function subtracts one. When the count reaches zero, nobody can reach the object, and CPython frees it at once, on that very line.

You can read the count with sys.getrefcount(x). It always reports one more than you expect, because passing x to the function creates a temporary extra reference for the duration of the call. The next script reads counts, and then uses __del__ (a method called just before an object is freed) to show when freeing happens.

refcount.py · Python 3.14runs offline
import sys
x = []
print("getrefcount([]) with one name:", sys.getrefcount(x))
y = x
print("after y = x                  :", sys.getrefcount(x))
del y
print("after del y                  :", sys.getrefcount(x))

class Order:
    def __init__(self, name): self.name = name
    def __del__(self): print(f"  __del__ runs for {self.name}")

print("create o1, then rebind the only name")
o = Order("o1")
o = Order("o2")           # o1 hits zero here, freed immediately
print("rebound; now del o")
del o
print("done")
refcount.py · output, Python 3.14.7runs offline
getrefcount([]) with one name: 2
after y = x                  : 3
after del y                  : 2
create o1, then rebind the only name
  __del__ runs for o1
rebound; now del o
  __del__ runs for o2
done

With one name, getrefcount reports 2 (the name, plus the call's own temporary). Adding y = x makes it 3, and del y returns it to 2. Then look at the order of the printed lines: __del__ runs for o1 appears immediately after o = Order("o2") and before the "rebound" line. The old object was freed the instant its last label moved.

This is deterministic freeing, and it is a real difference from Java: in CPython a file or lock held only by a local variable is released at the end of the function, without waiting for any collector. Programs have long leaned on that, sometimes unknowingly.

Refcounting has one blind spot: cycles. If object a points at b and b points at a, each keeps the other's count at one even after your code has dropped every outside name. Neither reaches zero.

For that case CPython adds a second mechanism, the cyclic garbage collector. Every so often it looks at container objects, finds groups that can only be reached from each other, and frees them. The next script builds exactly that cycle. It turns the automatic collector off first, so you can see the leak before triggering a collection by hand.

cycle_gc.py · Python 3.14runs offline
import gc

class Node:
    def __init__(self, name): self.name, self.other = name, None
    def __del__(self): print(f"  freed {self.name}")

gc.disable()                       # make the demo deterministic
a, b = Node("a"), Node("b")
a.other, b.other = b, a            # a cycle: each holds the other
print("del a, del b ...")
del a, b
print("no __del__ output yet: both still have refcount 1 from each other")
print("gc.collect() returned:", gc.collect())
print("thresholds:", gc.get_threshold(), "counts:", gc.get_count())
cycle_gc.py · output, Python 3.14.7runs offline
del a, del b ...
no __del__ output yet: both still have refcount 1 from each other
  freed a
  freed b
gc.collect() returned: 2
thresholds: (2000, 10, 10) counts: (2, 0, 0)
Two objects in a cycle: reference counts over time 1 create a = Node() b = Node() a refs: 1 b refs: 1 2 link them a.other = b b.other = a a refs: 2 b refs: 2 3 del a, del b your names are gone a refs: 1 b refs: 1 4 gc.collect() the collector steps in a refs: 0 b refs: 0 Step 3: each object is still held by the other, so neither count reaches 0. Reference counting alone never frees them; the cyclic collector finds the closed group. Without a cycle: del a takes the count 1 to 0 and the object is freed on that very line.
Fig. 19.4 — Refcount timeline for a two-object cycle. After the last outside name is deleted, each object still has one reference (from the other), so only the cycle collector can free them.

After del a, b nothing is printed: both objects are still alive, each held by the other. Only when gc.collect() runs do the two freed lines appear, and collect() returns 2, the number of unreachable objects it found.

The collector uses generations. New objects start in generation 0, which is scanned often and cheaply. Objects that survive a scan move to generation 1, then to generation 2, which is scanned rarely because old objects are usually long-lived. The thresholds are a count of allocations that triggers each scan. On the course machine Python 3.14.7 printed (2000, 10, 10), while Python 3.12.3 printed (700, 10, 10), so the defaults differ between versions.

Python 3.14.0 to 3.14.4 shipped a new incremental cycle collector (two generations, smaller pauses). Because of reports of high memory use in production, Python 3.14.5 reverted it to the generational collector from 3.13, and Python 3.15 keeps that generational collector too. So on the course machine's 3.14.7 the collector is the classic one, which is why the thresholds above are a normal-looking triple.

Two practical tools follow from this. gc.disable() stops automatic cycle scans, which some latency-sensitive services do on purpose and then call gc.collect() at a convenient moment.

gc.freeze() moves every object that exists right now into a permanent generation the collector ignores; it is used before forking worker processes, so the collector never touches (and therefore never copies) the memory pages that parent and children share. Large Python shops such as Instagram have written about using this to cut memory in forked servers; the exact numbers are theirs, not ours.

Finally, __del__ deserves suspicion. It runs at a moment you do not choose: late for objects in cycles, not at all at interpreter shutdown in some cases, and exceptions inside it are printed and swallowed. For cleanup use a with block (section 03) or weakref.finalize, never __del__.

Java · Spring

A tracing collector walks from roots. Anything it cannot reach is garbage, cycles included. Freeing happens when it runs.

run_pricer.shruns offline
# illustrative: choose and watch a GC
java -XX:+UseG1GC -Xmx2g \
     -Xlog:gc -jar pricer.jar
# objects die when a collection
# finds them unreachable

Python

Counts free most objects instantly. A small collector handles only cycles, and you can call it by hand.

gc_calls.py (excerpt)runs offline
import gc
print(gc.get_threshold())
# plain objects die at refcount 0
gc.collect()   # frees only cycles

The shift: the JVM frees memory in batches at moments the collector picks; CPython frees most objects the instant the last reference goes, and uses a collector only for cycles.

The trade-offs are the real interview content. The JVM can compact memory and run collectors concurrently on other cores; its cost is unpredictable pause timing and a bigger heap. CPython frees promptly and uses less memory for simple programs; its cost is that every assignment writes to an object's count.

That write is also why the global interpreter lock existed. If two threads changed one count at the same instant without protection, the count would become wrong, and an object would be freed while still in use. One big lock was the simple fix. Free-threaded Python (section 05) changes how counts are kept so the lock can go, at a measurable single-thread cost.

Why the process stays big, and how to measure memory honestly

A worker process grows from 200 MB to 3 GB over a day. The team deletes a huge cache, memory use in the monitoring dashboard does not drop, and everyone concludes there is a leak. Sometimes there is, and sometimes not. You need tools that tell the two apart.

First, why the dashboard can stay high. Objects up to 512 bytes come from a fast small-object allocator called pymalloc. It asks the operating system for big blocks called arenas (about a megabyte each in recent versions), cuts them into small pools, and hands out slots. An arena is returned to the operating system only when every object in it has been freed. (The free-threaded build uses a different allocator, mimalloc, so this description is for the normal build.)

If one long-lived object sits in each arena, none can be returned, even though most of the memory inside is free and will be reused by later Python objects. The process keeps the memory, and the operating system's number (RSS, resident set size) stays high. This is fragmentation, not a leak, and it is normal behaviour.

The next question is how big things really are. sys.getsizeof(x) reports the bytes of that one object only. For a list, that is the array of pointers, not the things the pointers lead to. The script below compares it with tracemalloc, the standard-library tool that records every allocation.

getsizeof_vs_tracemalloc.py · Python 3.14runs offline
import sys, tracemalloc
tracemalloc.start()
words = [f"item-number-{i:04d}" for i in range(1000)]
current, peak = tracemalloc.get_traced_memory()
print("sys.getsizeof(words)      :", sys.getsizeof(words), "bytes  (just the list's pointer array)")
print("one string                :", sys.getsizeof(words[0]), "bytes")
print("sum of getsizeof(each)    :", sum(sys.getsizeof(w) for w in words) + sys.getsizeof(words), "bytes")
print("tracemalloc total         :", current, "bytes")
getsizeof_vs_tracemalloc.py · output, Python 3.14.7runs offline
sys.getsizeof(words)      : 8856 bytes  (just the list's pointer array)
one string                : 57 bytes
sum of getsizeof(each)    : 65856 bytes
tracemalloc total         : 66264 bytes

A list of 1,000 short strings reports 8,856 bytes. Each string is about 57 bytes, and adding them up (plus the list) gives 65,856. tracemalloc measured 66,264 bytes in total, which agrees. The honest number was almost eight times what getsizeof on the list suggested. For nested structures, never trust getsizeof on the outer object.

Now a leak. Pricer has a helper that caches line items per order and never evicts anything. The script takes a snapshot of memory after 1,000 orders, adds 5,000 more, takes a second snapshot, and asks tracemalloc which lines of source code account for the growth.

tracemalloc_leak.py · Python 3.14runs offline
import tracemalloc

CACHE = {}                          # the leak: nothing ever leaves

def price(order_id):
    CACHE[order_id] = ["line-%d" % i for i in range(20)]
    return CACHE[order_id]

tracemalloc.start()
for i in range(1000):               # warm up, take snapshot 1
    price(i)
snap1 = tracemalloc.take_snapshot()
for i in range(1000, 6000):         # five thousand more orders
    price(i)
snap2 = tracemalloc.take_snapshot()

for stat in snap2.compare_to(snap1, "lineno")[:3]:
    print(stat)
tracemalloc_leak.py · output, Python 3.14.7 (paths shortened)runs offline
tracemalloc_leak.py:6: size=7307 KiB (+6102 KiB), count=131997 (+110001), average=57 B
tracemalloc_leak.py:13: size=137 KiB (+137 KiB), count=5000 (+5000), average=28 B
<stdlib>/tracemalloc.py:560: size=328 B (+328 B), count=1 (+1), average=328 B

Read the first line like a bug report. Line 6, the line that builds the cached list, grew by 6,102 KiB and 110,001 objects, at an average of 57 bytes each. That is 5,000 list objects, the 5,000 pointer arrays behind them, and 100,000 strings, plus one resized dict table: precisely the shape of "a cache that keeps everything". The second line, 5,000 objects of 28 bytes each, is the order-id integers kept alive as dictionary keys.

The method generalises. Take a snapshot when the service is healthy, take another after the memory has grown, and compare. The top few lines name the code that is allocating and never releasing. This is how you answer "find the leak" in an interview: not by reading code, but by asking the interpreter who owns the memory.

Idiom: a cache that does not keep objects alive

The problem: a plain dict cache holds a strong reference to each value, so every object ever cached stays alive until someone removes it, even when no other code uses it any more.

How it works: a weak reference points at an object without increasing its reference count. When the last ordinary reference goes, the object is freed and the weak reference becomes empty. weakref.WeakValueDictionary is a dict whose values are held weakly, so entries vanish by themselves.

  1. Create the cache: cache = weakref.WeakValueDictionary().
  2. Store values: cache[key] = obj. The cache does not own obj; the caller does.
  3. Read with .get: an entry may have disappeared since you last looked, so always handle None.
weakref_cache.py · Python 3.14runs offline
import gc, weakref

class Quote:
    def __init__(self, n): self.n = n

strong = {}                              # an ordinary dict cache
weak = weakref.WeakValueDictionary()     # a cache that does not own its values

q1, q2 = Quote(1), Quote(2)
strong["q1"] = q1
weak["q2"] = q2
print("both alive         : strong", len(strong), " weak", len(weak))

del q1, q2                               # the caller drops its own names
gc.collect()
print("after callers drop : strong", len(strong), " weak", len(weak))
print("weak cache lookup  :", weak.get("q2"))
weakref_cache.py · output, Python 3.14.7runs offline
both alive         : strong 1  weak 1
after callers drop : strong 1  weak 0
weak cache lookup  : None

The ordinary dict still holds q1 after the callers dropped their names (strong 1): that is the leak. The weak cache emptied itself (weak 0), and a lookup returns None.

Value objects: money that cannot be edited

Once you know that names are labels and mutation leaks, a design rule appears: things that represent a value should be immutable. A price is a value. So is a tax rate, a coordinate or a date range. Nothing should be able to change a price after it is created.

Pricer represents money as a small class with an amount and a currency. The amount must not be a float, because floats cannot represent 0.1 exactly. The standard decimal.Decimal type stores exact decimal digits.

Idiom: the frozen value object

The problem: a mutable price object can be edited by any code that holds it, and cannot be a dict key or set member, so bugs hide in "who changed this?"

How it works: @dataclass(frozen=True, slots=True) generates the constructor, equality and hash from the fields, blocks assignment, and (with slots) skips the per-instance dictionary.

  1. Declare the fields with types: amount: Decimal, currency: str.
  2. Freeze it: frozen=True makes __setattr__ raise FrozenInstanceError, and makes the generated __hash__ use the fields.
  3. Return new values: an operation such as + builds and returns a new Money; nothing is edited in place.

The version without the idiom is any plain class whose fields can be assigned, and its failure is the surge-fee incident above. The version with the idiom follows.

frozen_value.py · Python 3.14runs offline
from dataclasses import dataclass, FrozenInstanceError
from decimal import Decimal

@dataclass(frozen=True, slots=True)
class Money:
    amount: Decimal
    currency: str = "INR"

    def __add__(self, other):
        if self.currency != other.currency:
            raise ValueError("currency mismatch")
        return Money(self.amount + other.amount, self.currency)

m = Money(Decimal("199.50"))
try:
    m.amount = Decimal("1")
except FrozenInstanceError as e:
    print("FrozenInstanceError:", e)
print("hash equal for equal values:", hash(m) == hash(Money(Decimal("199.50"))))
prices = {m: "biryani"}
print("usable as dict key:", prices[Money(Decimal("199.50"))])
print(m + Money(Decimal("0.50")))
print("float trap:", 0.1 + 0.2, " Decimal:", Decimal("0.1") + Decimal("0.2"))
with the idiom · frozen_value.py, Python 3.14.7runs offline
FrozenInstanceError: cannot assign to field 'amount'
hash equal for equal values: True
usable as dict key: biryani
Money(amount=Decimal('200.00'), currency='INR')
float trap: 0.30000000000000004  Decimal: 0.3

Assigning to m.amount raises FrozenInstanceError. Equal values hash alike, so Money(Decimal("199.50")) works as a dictionary key, and a second, separately built object finds the same entry. Adding 0.50 builds a new object (200.00). The last line shows why Decimal is used: floats give 0.30000000000000004 for 0.1 + 0.2, Decimals give 0.3.

Always build a Decimal from a string. Decimal(0.1) faithfully copies the float's error into the Decimal.

03 · The data modelThe Data Model: How len, for, with, + and .attr Really Work

Python's built-in functions and operators are thin wrappers that call methods with double underscores on the object's type. Learn which method each piece of syntax calls and you can make your own classes behave like built-ins, and you can predict what goes wrong when they do not.

Pricer has a small class, PriceRule, that holds a discount code and a percentage. The team keeps every active rule in a set so lookups are fast and duplicates disappear.

To test the rules, a developer adds an __eq__ method so that two rules with the same code and percentage compare equal. The tests pass, the change is reviewed in two minutes, and it goes out in the next deploy.

The deploy crashes at start-up, in the line that builds the rule cache. Every worker restarts in a loop, and the service is down until someone rolls back. The developer did not touch the cache code or the set.

Here is the failure, reproduced in a ten-line script.

unhashable_eq.py · Python 3.14runs offline
class PriceRule:
    def __init__(self, code, pct):
        self.code, self.pct = code, pct

    def __eq__(self, other):
        return (self.code, self.pct) == (other.code, other.pct)

print("hash slot:", PriceRule.__hash__)
cache = set()
try:
    cache.add(PriceRule("FIRST50", 50))
except TypeError as e:
    print("TypeError:", e)
unhashable_eq.py · output, Python 3.14.7runs offline
hash slot: None
TypeError: cannot use 'PriceRule' as a set element (unhashable type: 'PriceRule')

The first output line is the cause: PriceRule.__hash__ is now None. When a class defines __eq__ and does not define __hash__, Python sets __hash__ = None automatically. The reasoning is sound: if equality rules changed, the old identity-based hash could give two equal objects different hashes, which would break sets and dicts. So Python makes the class unhashable and makes you decide.

Java never does this; it lets you override equals and forget hashCode, and your HashSet quietly misbehaves. Python fails loudly. The fix needs a rule about equality and hashing together, covered by an idiom later in this section. First, the mechanism behind all of it.

Bridge: special methods are the protocol

When you write len(cart), Python does not look inside cart for a method named len. It calls type(cart).__len__(cart). The double-underscore names are called special methods (or "dunder" methods), and the built-in functions and operators are defined as calls to them.

The important word is type. The special method is looked up on the class, not on the individual object. The next script proves it by putting a __len__ on one instance, and then on the class.

len_on_type.py · Python 3.14runs offline
class Cart:
    def __init__(self, items): self.items = items
    def __len__(self): return len(self.items)

c = Cart(["a", "b", "c"])
print("len(c) =", len(c), "  c.__len__() =", c.__len__())
c.__len__ = lambda: 99                      # put a method on the INSTANCE
print("after instance patch: c.__len__() =", c.__len__(), "  len(c) =", len(c))
Cart.__len__ = lambda self: 7               # change the TYPE
print("after type patch    : len(c) =", len(c))

print("--- truthiness: __bool__ first, then __len__")
class Empty:
    def __len__(self): return 0
class Odd(Empty):
    def __bool__(self): return True
print("bool(Empty()) =", bool(Empty()), "  bool(Odd()) =", bool(Odd()))
len_on_type.py · output, Python 3.14.7runs offline
len(c) = 3   c.__len__() = 3
after instance patch: c.__len__() = 99   len(c) = 3
after type patch    : len(c) = 7
--- truthiness: __bool__ first, then __len__
bool(Empty()) = False   bool(Odd()) = True

Calling c.__len__() directly after the instance patch gives 99, because attribute lookup finds the instance's function first. But len(c) still gives 3: the built-in goes to the class and ignores the instance. Only when the class itself changed did len(c) become 7.

That rule explains many surprises: monkey-patching special methods on instances does nothing, and mocks need to patch the class. It is also a speed rule, because looking up a special method on the type avoids a slower search through the instance's dictionary.

The bottom half of the output shows truthiness. bool(x) (what if x: uses) first calls __bool__ if the type has it, and falls back to __len__, treating zero as false. A class with only __len__ returning 0 is false. Adding __bool__ that returns True overrides the length. That also shows the hidden risk of if not value:: it treats 0, "", [] and None identically, so a legitimate discount of 0 is treated as "no discount given".

Operators and NotImplemented

The expression a + b calls type(a).__add__(a, b). If that method returns the special value NotImplemented, Python then tries the reflected method on the other object, type(b).__radd__(b, a). Only when both decline does Python raise TypeError.

You return NotImplemented (do not raise) to say "I do not know how to add this type; ask the other side". This is what lets 1 + Money(...) be handled by Money even though int has never heard of it.

The classic place this bites is sum(). The built-in sum starts from the integer 0 and computes 0 + first + second + .... If your class defines only __add__, the very first step, 0 + Money, has no one to handle it.

radd_sum.py · Python 3.14runs offline
class Money:
    def __init__(self, paise): self.paise = paise
    def __add__(self, other):
        if not isinstance(other, Money):
            return NotImplemented
        return Money(self.paise + other.paise)
    def __repr__(self): return f"Money({self.paise})"

a, b = Money(100), Money(250)
print("a + b =", a + b)
try:
    sum([a, b])
except TypeError as e:
    print("sum() failed:", e)

Money.__radd__ = lambda self, other: self if other == 0 else NotImplemented
print("with __radd__ :", sum([a, b]))
radd_sum.py · output, Python 3.14.7runs offline
a + b = Money(350)
sum() failed: unsupported operand type(s) for +: 'int' and 'Money'
with __radd__ : Money(350)

Adding two Money objects works, but sum([a, b]) fails with a message about int and Money. The fix is a __radd__ that accepts the starting 0 and returns the other operand. The alternative is sum(items, start=Money(0)), which gives sum a starting value of the right type and needs no change to the class.

One more pair of special methods is worth getting right early. __repr__ is for developers: it appears in logs, tracebacks and in the display of a list of objects, and should be unambiguous, ideally something you could paste back into code. __str__ is for end users and is used by print and f-strings. If you write only one, write __repr__, because str() falls back to it.

repr_str.py · Python 3.14runs offline
from decimal import Decimal
class Money:
    def __init__(self, amount): self.amount = Decimal(amount)
    def __repr__(self): return f"Money({str(self.amount)!r})"   # for developers
    def __str__(self): return f"Rs {self.amount:,.2f}"          # for customers
m = Money("1234.5")
print(str(m), "|", repr(m), "|", [m])
print("eval(repr(m)).amount ==", eval(repr(m)).amount)
repr_str.py · output, Python 3.14.7runs offline
Rs 1,234.50 | Money('1234.5') | [Money('1234.5')]
eval(repr(m)).amount == 1234.5

The list shows Money('1234.5') with the repr, never the pretty string. A good __repr__ names the type and shows the values in a form that identifies them, so a log line is enough to reproduce a bug.

Idiom: keep __eq__ and __hash__ in agreement

The problem: adding __eq__ makes the class unhashable (the incident above). The tempting repair, adding a __hash__ on mutable fields, is worse: the object gets lost inside the set the moment a field changes.

How it works: the contract is one sentence: objects that compare equal must have equal hashes. A hash is used to pick a slot, so the hash must come from the same fields that equality compares, and those fields must never change while the object is in a set or used as a key.

  1. Decide what identity means: for a rule, the code and the percentage.
  2. Hash only immutable fields: hash((self.code, self.pct)), using the same fields as __eq__.
  3. Or let Python generate both: @dataclass(frozen=True) writes a matching __eq__ and __hash__ and forbids the mutation that would break them.

Without the idiom, there are two failures. The first is the unhashable class shown at the top of this section. The second is a hash written by hand on fields that can change:

eq_hash_contract.py · Python 3.14runs offline
from dataclasses import dataclass

class BadRule:                         # hash uses a field that can change
    def __init__(self, code, pct): self.code, self.pct = code, pct
    def __eq__(self, o): return (self.code, self.pct) == (o.code, o.pct)
    def __hash__(self): return hash((self.code, self.pct))

r = BadRule("FIRST50", 50)
seen = {r}
r.pct = 60                             # mutate AFTER it is in the set
print("rule in set after edit:", r in seen, "| set size:", len(seen))

@dataclass(frozen=True)
class Rule:                            # ✅ eq + hash generated from frozen fields
    code: str
    pct: int

s = {Rule("FIRST50", 50)}
print("frozen dataclass lookup:", Rule("FIRST50", 50) in s)
print("eq implies equal hash  :", hash(Rule("A", 1)) == hash(Rule("A", 1)))
eq_hash_contract.py · output, Python 3.14.7runs offline
rule in set after edit: False | set size: 1
frozen dataclass lookup: True
eq implies equal hash  : True

The first output line is the silent failure. After r.pct = 60, the rule is still in the set (size 1), but r in seen is False. The set stored the rule in the slot for its old hash; the new hash points elsewhere, so the object can no longer be found, and it can never be removed. The rule is leaked inside its own container.

The frozen dataclass at the bottom is the repair: the lookup works, and because the fields cannot be assigned, the failure above cannot happen.

Java · Spring

You override both methods by hand. A forgotten hashCode compiles and misbehaves quietly in a HashSet.

PriceRule.javaruns offline
// illustrative
@Override boolean equals(Object o) {
  return o instanceof PriceRule r
    && code.equals(r.code) && pct == r.pct;
}
@Override int hashCode() {
  return Objects.hash(code, pct);
}

Python

Defining only __eq__ removes hashing altogether, and a frozen dataclass writes both together.

rule.py (excerpt)runs offline
@dataclass(frozen=True)
class Rule:
    code: str
    pct: int
# __eq__ and __hash__ generated,
# fields cannot change afterwards

The shift: Java trusts you to keep the pair consistent; Python refuses to hash a class with a custom equality until you either supply a matching hash or freeze the fields.

Bridge: iteration, one level down

Two words are used loosely and must be kept apart. An iterable is anything you can loop over: it has __iter__, which returns an iterator. An iterator is the object that remembers a position: it has __next__, which returns the next item or raises StopIteration when there are no more, and its own __iter__ returns itself.

A list is iterable, but it is not an iterator. Every for loop asks it for a fresh iterator, so you can loop over a list as many times as you like. A generator is an iterator, so there is only one position, and when it reaches the end it stays at the end.

iteration.py · Python 3.14runs offline
def prices():
    yield 100
    yield 250

g = prices()
print("first pass :", list(g))
print("second pass:", list(g), "<- exhausted")
print("iter(g) is g:", iter(g) is g, "(an iterator returns itself)")

data = [10, 20, 30]
print("list is iterable but not an iterator:", iter(data) is data, hasattr(data, "__next__"))

# what `for x in data:` does
it = iter(data)
while True:
    try:
        x = next(it)
    except StopIteration:
        break
    print("  body sees", x)
iteration.py · output, Python 3.14.7runs offline
first pass : [100, 250]
second pass: [] <- exhausted
iter(g) is g: True (an iterator returns itself)
list is iterable but not an iterator: False False
  body sees 10
  body sees 20
  body sees 30

The second pass over the generator prints [], with no error. That silent emptiness is a common production bug: a function receives "an iterable of prices", loops over it once to validate and a second time to total it, and the total is always zero when the caller passed a generator.

The while loop at the bottom is what for x in data: really does. It calls iter(data) once, then calls next repeatedly, and exits the loop when StopIteration is raised. That is the whole protocol; it is why files, dict views, database cursors and your own classes can all be used in a for loop.

The defence is a rule rather than a trick. If a function needs to read its input twice, either accept a list or call list(items) on entry, or make a class whose __iter__ builds a fresh generator each time so that it can be looped over repeatedly.

Bridge: context managers, one level down

A with statement guarantees that cleanup code runs, whether the body finishes or fails. The pattern with thing as x: body behaves roughly as follows.

  1. Enter: call thing.__enter__(); whatever it returns becomes x.
  2. Run the body inside a try.
  3. Exit: always call thing.__exit__(exc_type, exc, tb), with three Nones if the body succeeded, or the exception's details if it failed.
  4. Decide: if __exit__ returns a true value the exception is swallowed; otherwise it continues up the stack.
context_manager.py · Python 3.14runs offline
import contextlib

class Tx:
    def __init__(self, name): self.name = name
    def __enter__(self):
        print(f"  enter {self.name}"); return self
    def __exit__(self, exc_type, exc, tb):
        print(f"  exit  {self.name}  exc_type={exc_type.__name__ if exc_type else None}")
        return exc_type is ValueError          # True swallows the exception

print("1) normal")
with Tx("a"): print("  body")
print("2) ValueError is swallowed")
with Tx("b"): raise ValueError("bad code")
print("  ...program continues")
print("3) KeyError is not swallowed")
try:
    with Tx("c"): raise KeyError("x")
except KeyError: print("  KeyError escaped")

@contextlib.contextmanager
def tx(name):
    print(f"  enter {name}")
    try: yield name
    finally: print(f"  exit  {name}")

print("4) same thing with @contextmanager")
with tx("d"): print("  body")

print("5) ExitStack for N resources")
with contextlib.ExitStack() as stack:
    for n in ("r1", "r2", "r3"):
        stack.enter_context(tx(n))
    print("  body")
context_manager.py · output, Python 3.14.7runs offline
1) normal
  enter a
  body
  exit  a  exc_type=None
2) ValueError is swallowed
  enter b
  exit  b  exc_type=ValueError
  ...program continues
3) KeyError is not swallowed
  enter c
  exit  c  exc_type=KeyError
  KeyError escaped
4) same thing with @contextmanager
  enter d
  body
  exit  d
5) ExitStack for N resources
  enter r1
  enter r2
  enter r3
  body
  exit  r3
  exit  r2
  exit  r1

Case 2 is the surprise: the ValueError vanishes. __exit__ returned True for ValueError, so the program printed "...program continues" as if nothing had happened. Case 3 shows a different error (KeyError) passing through. Swallowing is powerful and dangerous; contextlib.suppress uses it deliberately, but a careless return True hides real bugs.

Writing a class with two methods is long for what is usually a three-line idea. @contextmanager lets a generator do the job: everything before yield is the enter step, the yielded value is bound to as, and everything after is the exit step, which belongs in a finally so it runs on errors. Case 5 shows ExitStack, which lets you enter any number of context managers in a loop and unwinds them in reverse order.

Idiom: put cleanup in a context manager

The problem: code that acquires a resource and releases it on the last line leaks the resource whenever an exception happens in between.

How it works: move acquire and release into a context manager whose release runs in finally, and use with at every call site.

  1. Write it once: a @contextmanager generator with try: yield ... finally: release.
  2. Use it everywhere: with connection(): ...; the call site cannot forget the release.
  3. For many resources: ExitStack, instead of nesting with blocks.

Without the idiom, pricer's batch function releases its pooled connection on the last line. Three batches run; the second has a bad order:

no_context_manager.py · Python 3.14runs offline
open_connections = 0

def reprice_batch(orders):
    global open_connections
    open_connections += 1          # acquire a pooled connection
    print("  acquired, open =", open_connections)
    for o in orders:
        if o is None:
            raise RuntimeError("bad order")   # ❌ TRAP: the release line below is skipped
    open_connections -= 1          # release
    print("  released, open =", open_connections)

for batch in ([1, 2], [1, None], [3]):
    try:
        reprice_batch(batch)
    except RuntimeError as e:
        print("  caught:", e)
print("connections still open:", open_connections)
without the idiom · no_context_manager.py, Python 3.14.7runs offline
  acquired, open = 1
  released, open = 0
  acquired, open = 1
  caught: bad order
  acquired, open = 2
  released, open = 1
connections still open: 1

The failing batch printed "acquired, open = 1" and never "released". It left one connection permanently open, and the third batch saw open = 2. One bad order per hour is enough to exhaust a pool of 50 connections in two days. Now the same three batches with the idiom:

tx_idiom.py · Python 3.14runs offline
from contextlib import contextmanager

open_connections = 0

@contextmanager
def connection():
    global open_connections
    open_connections += 1
    print("  acquired, open =", open_connections)
    try:
        yield
    finally:                        # ✅ runs on success AND on error
        open_connections -= 1
        print("  released, open =", open_connections)

def reprice_batch(orders):
    with connection():
        for o in orders:
            if o is None:
                raise RuntimeError("bad order")

for batch in ([1, 2], [1, None], [3]):
    try:
        reprice_batch(batch)
    except RuntimeError as e:
        print("  caught:", e)
print("connections still open:", open_connections)
with the idiom · tx_idiom.py, Python 3.14.7runs offline
  acquired, open = 1
  released, open = 0
  acquired, open = 1
  released, open = 0
  caught: bad order
  acquired, open = 1
  released, open = 0
connections still open: 0

Every "acquired" is followed by a "released", including the failing batch, and the final count is 0.

Java · Spring

Try-with-resources closes anything that implements AutoCloseable, even if the body throws.

Batch.javaruns offline
// illustrative
try (Connection c = pool.get()) {
  reprice(c, orders);
}   // c.close() always runs

Python

A with block calls __exit__ in the same situations, and the manager can be a generator.

tx_idiom.py (excerpt)runs offline
def reprice_batch(orders):
    with connection():
        for o in orders:
            check(o)
# release runs in finally

The shift: Java ties cleanup to a type that implements AutoCloseable; Python ties it to any object with __enter__ and __exit__, and a three-line generator can become one.

Bridge: how obj.attr is really looked up

Writing obj.price looks like reading a field. It is actually a small search with a fixed order, and knowing the order explains @property, methods, @staticmethod, __slots__ and several mysterious bugs. The search has four steps, and it stops at the first one that finds something.

How obj.attr is looked up 1 Data descriptor found on type(obj)'s MRO? has __set__ or __delete__ yes Use it: call its __get__(obj, type) no 2 Name in obj.__dict__? the instance's own dictionary yes Return the instance value no 3 Non-data descriptor or class attribute? found along the MRO yes Function becomes bound method; else as is no 4 Does the class define __getattr__? last-chance hook yes Call __getattr__(obj, name) No -> AttributeError no
Fig. 19.5 — The order in which obj.attr is resolved. A data descriptor on the class beats the instance dictionary; the instance dictionary beats methods and other non-data descriptors.
  1. Data descriptor on the class: Python looks through the class and its parents (the MRO, explained below) for the name. If it finds an object that has __set__ or __delete__ (a data descriptor), that object wins, even over the instance's own dictionary.
  2. Instance dictionary: otherwise, if the name is in obj.__dict__, that value is returned.
  3. Non-data descriptor or class attribute: otherwise the class lookup result is used. A plain function here is turned into a bound method by its __get__. Other class attributes are returned as they are.
  4. The __getattr__ hook: if everything failed and the class defines __getattr__, it is called with the name; otherwise AttributeError.

An object that defines __get__ is a descriptor. If it also defines __set__ or __delete__ it is a data descriptor; if it only has __get__ it is a non-data descriptor. The script below makes both kinds print a message every time they are used, so the order from the figure becomes visible.

attr_lookup_trace.py · Python 3.14runs offline
class Loud:                                   # data descriptor: has __get__ AND __set__
    def __set_name__(self, owner, name): self.name = name
    def __get__(self, obj, owner=None):
        print(f"    Loud.__get__ for {self.name}"); return "from data descriptor"
    def __set__(self, obj, value): print(f"    Loud.__set__ {self.name}={value!r}")

class Quiet:                                  # non-data descriptor: __get__ only
    def __set_name__(self, owner, name): self.name = name
    def __get__(self, obj, owner=None):
        print(f"    Quiet.__get__ for {self.name}"); return "from non-data descriptor"

class Pricer:
    rate = Loud()
    note = Quiet()
    other = Quiet()
    version = "class attribute"
    def method(self): return "method"
    def __getattr__(self, name):
        print(f"    __getattr__({name!r}) called last"); return "fallback"

p = Pricer()
p.__dict__["rate"] = "instance dict value"
p.__dict__["note"] = "instance dict value"
p.__dict__["method"] = "instance dict shadows the method"
print("rate    ->", p.rate)
print("note    ->", p.note)
print("other   ->", p.other)
print("version ->", p.version)
print("method  ->", p.method)
print("missing ->", p.missing)
attr_lookup_trace.py · output, Python 3.14.7runs offline
    Loud.__get__ for rate
rate    -> from data descriptor
note    -> instance dict value
    Quiet.__get__ for other
other   -> from non-data descriptor
version -> class attribute
method  -> instance dict shadows the method
    __getattr__('missing') called last
missing -> fallback

The script puts a value in the instance dictionary for rate, note and method, and then reads each. The results line up with the four steps.

rate is a data descriptor, so it is used even though the instance dictionary has a competing value (step 1). note is a non-data descriptor, so the instance dictionary wins and Quiet.__get__ is never called (step 2 before step 3). other has no entry in the instance dictionary, so the non-data descriptor runs (step 3). version is a plain class attribute (step 3).

method shows that a method can be shadowed: a function is only a non-data descriptor, so an entry with the same name in the instance dictionary replaces it. missing found nothing anywhere, so __getattr__ was called last.

A related method, __getattribute__, is called on every attribute access and implements this whole search. Override it only if you must, and reach the real attribute through super().__getattribute__(name) or object.__getattribute__(self, name); touching self.x inside it calls it again and recurses forever.

Descriptors you already use

Functions, property, staticmethod and classmethod are all descriptors. The next script asks each how it is stored in the class and whether it has __get__ and __set__.

descriptors_everywhere.py · Python 3.14runs offline
class Pricer:
    def method(self): return "hi"
    @property
    def rate(self): return 8
    @staticmethod
    def s(): return "s"
    @classmethod
    def c(cls): return cls.__name__

p = Pricer()
for name in ("method", "rate", "s", "c"):
    d = Pricer.__dict__[name]
    print(f"{name:7} stored as {type(d).__name__:14} __get__: {hasattr(d, '__get__')!s:5} __set__: {hasattr(d, '__set__')}")

f = Pricer.__dict__["method"]
print("function.__get__(p, Pricer) ->", f.__get__(p, Pricer))
print("same as p.method? ", p.method == f.__get__(p, Pricer))
descriptors_everywhere.py · output, Python 3.14.7runs offline
method  stored as function       __get__: True  __set__: False
rate    stored as property       __get__: True  __set__: True
s       stored as staticmethod   __get__: True  __set__: False
c       stored as classmethod    __get__: True  __set__: False
function.__get__(p, Pricer) -> <bound method Pricer.method of <__main__.Pricer object at 0x72d442794590>>
same as p.method?  True

All four have __get__. Only property also has __set__, which is why a property beats a value in the instance dictionary and a method does not. The last two lines show the secret behind methods: Pricer.__dict__["method"] is a plain function. When you write p.method, the function's __get__(p, Pricer) runs and returns a bound method, a small object that remembers p and passes it as self. That is the entire mechanism of self.

One extra hook completes the picture. When a class body finishes, Python calls __set_name__(owner, name) on every descriptor in it, so a descriptor learns the attribute name it was assigned to. The next idiom uses it.

Idiom: a reusable validated field as a descriptor

The problem: validation written with @property is the same four lines for every field in every class. With 20 model classes and three numeric fields each, that is about 60 copies of one rule, and the copies drift.

How it works: write the rule once as a descriptor class with __get__ and __set__. Assign an instance of it as a class attribute in any class that needs the check.

  1. Learn the name: __set_name__ stores the field's name so the descriptor knows where to keep the value (here _price on the instance).
  2. Check on write: __set__ validates and stores. Every assignment, including the one in __init__, goes through it.
  3. Return itself on class access: if obj is None the attribute was read on the class, and returning self lets tools inspect the field.

Without the idiom, two fields in one class:

property_boilerplate.py · Python 3.14runs offline
class Item:
    def __init__(self, price, qty):
        self.price, self.qty = price, qty

    @property
    def price(self): return self._price
    @price.setter
    def price(self, v):
        if v <= 0: raise ValueError(f"price must be positive, got {v!r}")
        self._price = v

    @property
    def qty(self): return self._qty
    @qty.setter
    def qty(self, v):                     # ❌ TRAP: the same four lines again,
        if v <= 0: raise ValueError(f"qty must be positive, got {v!r}")   # per field, per class
        self._qty = v

try:
    Item(-5, 1)
except ValueError as e:
    print("rejected:", e)
without the idiom · property_boilerplate.py, Python 3.14.7runs offline
rejected: price must be positive, got -5

That is 12 lines for two fields, and the code must be pasted into every other class that has a numeric field. With the idiom:

descriptor_positive.py · Python 3.14runs offline
class Positive:
    def __set_name__(self, owner, name):
        self.private = "_" + name
    def __get__(self, obj, owner=None):
        if obj is None:
            return self
        return getattr(obj, self.private)
    def __set__(self, obj, value):
        if not isinstance(value, (int, float)) or value <= 0:
            raise ValueError(f"{self.private[1:]} must be a positive number, got {value!r}")
        setattr(obj, self.private, value)

class Item:
    price = Positive()
    qty = Positive()
    def __init__(self, price, qty): self.price, self.qty = price, qty

class Fee:
    amount = Positive()                 # reused in another class
    def __init__(self, amount): self.amount = amount

it = Item(120, 2)
print("ok:", it.price, it.qty)
for bad in (lambda: Item(-5, 1), lambda: Item(10, 0), lambda: Fee("x")):
    try: bad()
    except ValueError as e: print("rejected:", e)
print("stored in __dict__ as:", it.__dict__)
with the idiom · descriptor_positive.py, Python 3.14.7runs offline
ok: 120 2
rejected: price must be a positive number, got -5
rejected: qty must be a positive number, got 0
rejected: amount must be a positive number, got 'x'
stored in __dict__ as: {'_price': 120, '_qty': 2}

The three bad values (-5, 0 and the string "x") are rejected with an error message that names the field, and the same Positive class serves Item and Fee without a copy. The last line shows where the value really lives: _price and _qty in the instance dictionary, while the class attributes price and qty are the descriptors.

This is also the idea inside Django model fields, SQLAlchemy columns and Pydantic fields: a class attribute that is not a plain value but an object that controls reads and writes.

Bridge: __slots__, what it saves and what it costs

By default every instance carries a dictionary, obj.__dict__, holding its attributes. That dictionary is what lets you add any attribute at any time, and it costs memory. Declaring __slots__ = ("a", "b", "c") in the class tells Python to store those attributes in fixed positions inside the object and to skip the dictionary.

The expected win is memory, so measure it rather than assume it. The script builds one million instances of each version and asks tracemalloc how much memory they hold, then times reading an attribute 5,000,000 times.

slots_memory.py · Python 3.14runs offline
import timeit, tracemalloc

class Plain:
    def __init__(self, a, b, c): self.a, self.b, self.c = a, b, c

class Slotted:
    __slots__ = ("a", "b", "c")
    def __init__(self, a, b, c): self.a, self.b, self.c = a, b, c

def measure(cls):
    tracemalloc.start()
    objs = [cls(1, 2, 3) for _ in range(1_000_000)]
    current, _ = tracemalloc.get_traced_memory()
    tracemalloc.stop()
    return current / 1e6, objs

mb_plain, objs = measure(Plain);   del objs
mb_slots, objs = measure(Slotted); del objs
print(f"1,000,000 Plain   instances: {mb_plain:7.1f} MB")
print(f"1,000,000 Slotted instances: {mb_slots:7.1f} MB   ({mb_plain / mb_slots:.1f}x smaller)")

p, s = Plain(1, 2, 3), Slotted(1, 2, 3)
n = 5_000_000
print(f"read p.a, {n:,} times: plain {timeit.timeit('p.a', globals=globals(), number=n):.3f} s, "
      f"slotted {timeit.timeit('s.a', globals=globals(), number=n):.3f} s")
try:
    s.extra = 1
except AttributeError as e:
    print("slotted new attribute ->", e)
print("has __dict__: plain", hasattr(p, "__dict__"), " slotted", hasattr(s, "__dict__"))
slots_memory.py · output, Python 3.14.7runs offline
1,000,000 Plain   instances:   104.5 MB
1,000,000 Slotted instances:    64.4 MB   (1.6x smaller)
read p.a, 5,000,000 times: plain 0.060 s, slotted 0.057 s
slotted new attribute -> 'Slotted' object has no attribute 'extra' and no __dict__ for setting new attributes
has __dict__: plain True  slotted False

One million plain instances held 104.5 MB, and one million slotted instances held 64.4 MB: 1.6 times smaller, about 40 bytes saved per object. That is a solid saving for a record-heavy program, but smaller than older articles quote. Since Python 3.11 plain instances store their attributes in a compact, dictionary-free layout until something actually asks for __dict__, which narrows the gap. Measure on your own version.

The speed difference is within noise: 0.060 s against 0.057 s for five million reads. Slots are a memory tool, not a speed tool, so do not add them hoping for faster attribute access.

The costs are real. Slotted instances cannot gain new attributes (the error in the output says so), they have no __dict__, and multiple inheritance gets awkward because a class can only inherit from one parent with a non-empty layout. They also do not combine with some features that need to attach attributes, such as certain caching decorators.

Idiom: slots for millions of small records

The problem: a program that holds millions of small objects pays for a dictionary per object. Pricer's nightly report keeps one object per order line, a million lines at a time.

How it works: list the attribute names in __slots__, or ask for it with @dataclass(slots=True), which writes the slots for you and keeps the dataclass features.

  1. Measure first: use tracemalloc on a realistic count, as in the run above. If the saving is small, skip it.
  2. Add slots: @dataclass(slots=True), or __slots__ in a plain class.
  3. Accept the limits: no new attributes, and care with inheritance.

The "without" and "with" runs are the two lines of the same output above: 104.5 MB for the plain class, 64.4 MB for the slotted one, with the same fields and the same million objects.

Bridge: the MRO and super()

A class can have several parents. When two parents both define a method, Python has to decide which wins, and where a shared grandparent goes. The answer is a single ordered list called the method resolution order (MRO), built by an algorithm called C3 linearisation.

C3 guarantees three things: a class always comes before its parents, the order in which you listed a class's bases is preserved, and every class appears exactly once. Lookups follow that list from left to right, which is what step 1 and step 3 of the attribute search mean by "along the MRO".

The smallest interesting case is a diamond. One base class, two classes that extend it, and one class that extends both. The figure shows it for pricer's rule classes.

Inheritance diamond C3 linearisation: Promo.__mro__ Rule Taxed(Rule) Discounted(Rule) Promo(Taxed, Discounted) arrows point from child up to parent 1 Promo 2 Taxed 3 Discounted 4 Rule 5 object Rule comes after BOTH of its children
Fig. 19.6 — A diamond and its MRO. C3 puts every class before its parents and keeps each class's listed bases in order, so Rule appears once, after both Taxed and Discounted.
mro_diamond.py · Python 3.14runs offline
class Rule:
    def __init__(self, **kw):
        print("  Rule.__init__")
        super().__init__(**kw)
class Taxed(Rule):
    def __init__(self, tax=0, **kw):
        print("  Taxed.__init__"); self.tax = tax
        super().__init__(**kw)
class Discounted(Rule):
    def __init__(self, pct=0, **kw):
        print("  Discounted.__init__"); self.pct = pct
        super().__init__(**kw)
class Promo(Taxed, Discounted):
    def __init__(self, **kw):
        print("  Promo.__init__")
        super().__init__(**kw)

print([c.__name__ for c in Promo.__mro__])
p = Promo(tax=8, pct=10)
print("tax", p.tax, "pct", p.pct)
mro_diamond.py · output, Python 3.14.7runs offline
['Promo', 'Taxed', 'Discounted', 'Rule', 'object']
  Promo.__init__
  Taxed.__init__
  Discounted.__init__
  Rule.__init__
tax 8 pct 10

The first line is the MRO: Promo, Taxed, Discounted, Rule, object. Notice that Rule comes after both of its children, and that Taxed comes before Discounted because that is the order in class Promo(Taxed, Discounted).

The remaining lines show super() at work. super() does not mean "my parent". It means "the next class after me in the MRO of the object's real type". Inside Taxed.__init__, super().__init__(**kw) calls Discounted.__init__, not Rule.__init__, because the object being built is a Promo.

This is why super() is called cooperative. Every class in the chain does its own work, takes the arguments it knows (tax, pct), and passes the rest on with **kw. The chain visits each class once, in MRO order, and Rule.__init__ runs exactly once, at the end. If any class in the chain forgets to call super().__init__, the classes after it are skipped silently.

A mixin is a small class meant to be added to others for one behaviour (for example a JsonMixin that adds to_json). Mixins work because of the MRO, and they are cooperative by the same rule: put them to the left of the main base, never give them required constructor arguments, and let them call super().

Bridge: class creation, one level down

A class statement is executable code, like def. Python runs the body as a small block that fills a dictionary (the namespace), then hands that dictionary to the thing that builds the class, the metaclass, which is type unless you say otherwise. After the class exists, Python calls a few hooks in a fixed order.

What class Child(Base): ... does, in order 2 Run the class body fills a namespace dict price = Field() 3 Metaclass builds class type(name, bases, ns) Meta.__new__ runs here 4 __set_name__ called descriptor.__set_name__() called by type.__new__ 5 __init_subclass__ runs parent.__init_subclass__() registries live here 6 Class decorators run gets the finished class may return another object 7 The name is bound Child points at the class earlier code never saw it Steps 4 and 5 both happen before the line class ... finishes.
Fig. 19.7 — Class creation pipeline. Step 1 is the class statement itself; the numbers 2 to 7 match the lines the run later in this section prints.

The next script puts a print statement in every hook so the order is visible. It defines a metaclass, a descriptor with __set_name__, a parent with __init_subclass__, and a class decorator.

class_creation_order.py · Python 3.14runs offline
print("1. about to run the class body")
class Meta(type):
    def __new__(mcls, name, bases, ns):
        if name == 'Child': print(f"3. Meta.__new__ builds {name!r} from namespace keys {sorted(k for k in ns if not k.startswith('__'))}")
        return super().__new__(mcls, name, bases, ns)

class Field:
    def __set_name__(self, owner, name): print(f"4. Field.__set_name__ -> {owner.__name__}.{name}")

class Base(metaclass=Meta):
    def __init_subclass__(cls, **kw):
        print(f"5. Base.__init_subclass__ for {cls.__name__}")
        super().__init_subclass__(**kw)

def deco(cls):
    print(f"6. class decorator sees {cls.__name__}"); return cls

@deco
class Child(Base):
    print("2. class body runs (a function-like block that fills a namespace)")
    price = Field()
print("7. name Child is bound only now:", Child)
class_creation_order.py · output, Python 3.14.7runs offline
1. about to run the class body
2. class body runs (a function-like block that fills a namespace)
3. Meta.__new__ builds 'Child' from namespace keys ['price']
4. Field.__set_name__ -> Child.price
5. Base.__init_subclass__ for Child
6. class decorator sees Child
7. name Child is bound only now: <class '__main__.Child'>

The order is exactly the figure's: body (2), metaclass (3), __set_name__ (4), the parent's __init_subclass__ (5), the decorator (6), and only then is the name Child bound (7). Note that the body runs before the metaclass sees anything, because the metaclass needs the finished namespace.

That is why __init_subclass__ is the preferred hook. It runs for every subclass, at the moment of creation, with no custom metaclass needed. A metaclass is still the right tool when you need to change how the class is built: rewriting the namespace before the class exists, or customising the class's own behaviour such as isinstance checks. Abstract base classes (ABCMeta) and ORM models use it. For everything else, prefer __init_subclass__ and class decorators.

Idiom: a plugin registry with __init_subclass__

The problem: a registry that people have to update by hand loses entries. Someone writes a new pricing rule, forgets one line, and the code FLAT20 raises KeyError on one particular Thursday.

How it works: the parent class defines __init_subclass__, which Python calls for every new subclass. The hook records the subclass in the registry under the code given as a class keyword.

  1. Declare: class First50(Rule, code="FIRST50") passes code as a class keyword argument.
  2. Register: Rule.__init_subclass__(cls, code=...) stores Rule.registry[code] = cls.
  3. Reject mistakes at definition time: a subclass that forgets code raises TypeError while the module is imported, not in production.

Without the idiom, registration is a manual line that one developer forgot:

manual_registry.py · Python 3.14runs offline
RULES = {}

class First50:
    code = "FIRST50"
class Flat20:
    code = "FLAT20"

RULES[First50.code] = First50          # someone remembered
# RULES[Flat20.code] = Flat20          # ❌ TRAP: someone forgot this line

for code in ("FIRST50", "FLAT20"):
    try:
        print(code, "->", RULES[code].__name__)
    except KeyError:
        print(code, "-> KeyError: never registered")
without the idiom · manual_registry.py, Python 3.14.7runs offline
FIRST50 -> First50
FLAT20 -> KeyError: never registered

The unregistered rule is found only at lookup time, in production. With the idiom:

init_subclass_registry.py · Python 3.14runs offline
class Rule:
    registry = {}
    def __init_subclass__(cls, code=None, **kw):
        super().__init_subclass__(**kw)
        if code is None:
            raise TypeError(f"{cls.__name__} must declare code=...")
        Rule.registry[code] = cls
    def apply(self, total): raise NotImplementedError

class First50(Rule, code="FIRST50"):
    def apply(self, total): return total * 0.5
class Flat20(Rule, code="FLAT20"):
    def apply(self, total): return total - 20

print("registered:", sorted(Rule.registry))
print("FIRST50 on 400 ->", Rule.registry["FIRST50"]().apply(400))
try:
    class Oops(Rule): pass
except TypeError as e:
    print("TypeError:", e)
with the idiom · init_subclass_registry.py, Python 3.14.7runs offline
registered: ['FIRST50', 'FLAT20']
FIRST50 on 400 -> 200.0
TypeError: Oops must declare code=...

Both rules registered themselves on definition. The class Oops, which declares no code, failed immediately with a clear message, at the line where the mistake was written.

dataclass, NamedTuple, attrs or Pydantic: choosing a record type

Most Python programs spend their life moving small records around. Four tools generate the boilerplate, and they differ in what they check and what they cost. First, the dataclass error every team meets once.

dataclass_default.py · Python 3.14runs offline
from dataclasses import dataclass, field
try:
    @dataclass
    class Order:
        id: str
        codes: list = []              # ❌ TRAP
except ValueError as e:
    print("ValueError:", e)

@dataclass
class Order:                          # ✅
    id: str
    codes: list = field(default_factory=list)

a, b = Order("o-1"), Order("o-2")
a.codes.append("FIRST50")
print("a:", a.codes, " b:", b.codes)
dataclass_default.py · output, Python 3.14.7runs offline
ValueError: mutable default <class 'list'> for field codes is not allowed: use default_factory
a: ['FIRST50']  b: []

A dataclass refuses a list as a default when the class is created, with a message that names the fix: default_factory. It is the same bug as the codes=[] default, caught at import time by a rule in the dataclass machinery. A field(default_factory=list) builds a new list for each instance, and the output shows the two orders no longer sharing codes.

Four ways to define a record: pick by what must be checked
OptionPick it whenCost or catch
@dataclass (standard library)Internal data you trust. You want generated __init__, __eq__, __repr__, with frozen=True and slots=True available.Type hints are not enforced; passing a string for an int is accepted silently. No parsing or validation.
typing.NamedTupleA tiny, immutable record that must also behave like a tuple (unpacking, indexing, usable as a key).Immutable only; no per-field defaults beyond simple ones, no methods that change state. Behaves as a tuple, so two different types with equal values compare equal.
attrs (third-party)You want dataclass features plus validators, converters and more control, or you maintain a library.One more dependency, and a second way to do what the standard library mostly does.
Pydantic BaseModelData from outside your process: JSON requests, config files, message payloads. It parses, converts types and reports readable errors.Slower to create than a dataclass, and a heavier dependency. Pointless for internal objects that were already validated at the edge.

The rule of thumb is to validate at the edge and keep the inside plain. A request arrives as untrusted JSON: Pydantic turns it into typed objects and rejects the bad ones. Past that point, frozen dataclasses move the validated values around cheaply. Chapter E20 builds exactly that split with FastAPI.

Say it in one breath

If you can say the next paragraph without looking, you have the first three sections. "Names are labels pointing at objects, so assignment moves labels and mutation changes shared objects. Defaults are built once when def runs, so I use None.

CPython frees an object the moment its reference count hits zero and uses a cycle collector for the rest. Built-ins call special methods on the type, so a class defining __eq__ loses its hash. Attribute lookup goes data descriptor, instance dictionary, class attribute, __getattr__. A class statement runs its body first, then the metaclass, then __set_name__ and __init_subclass__."

04 · FunctionsFunctions, Closures, Decorators and Generators

In Python a function is an ordinary object: you can store it, pass it, attach attributes to it, and build new ones at run time. Closures, decorators and generators are three consequences of that one idea. Each has a trap that looks like a bug in Python and is really a rule you have not met yet.

Here is an incident from the pricer team. The scheduler has to reprice every tenant's menu each night, and the developer wrote a loop that registers one handler per tenant. The handler is a one-line lambda that calls reprice(tenant).

The night run starts. There are 40 tenants, so there are 40 handlers. All 40 of them reprice the same tenant: the last one in the list. That tenant gets 40 times the normal work, and the other 39 tenants get no repricing at all until someone notices in the morning.

Nothing crashed and no error was logged. The code did exactly what Python says it should. Here it is with only three tenants.

Make the invisible visible: three handlers, one per tenant, called one after the other.

late_binding.py · Python 3.14runs offline
# pricer scheduler: one handler per tenant
tenants = ["acme", "bolt", "crisp"]
handlers = []
for tenant in tenants:
    handlers.append(lambda: f"repricing {tenant}")   # ❌ TRAP: captures the variable

for h in handlers:
    print(h())
print("loop variable after the loop:", tenant)
output (real run)runs offline
repricing crisp
repricing crisp
repricing crisp
loop variable after the loop: crisp

Why: the lambda does not remember the value "acme". It remembers the variable called tenant, and it reads that variable only when it is called. By then the loop has finished and the variable holds "crisp".

To see why, we need four small mechanisms, one level down each: functions as objects, the rules for finding a name (scope), the cells that closures use, and then the decorators and generators built on top. We start with the first.

Bridge: a function is an object, one level down

When Python runs a def statement it builds a function object and binds a name to it. That is all def does. The object has a type (function), attributes, and a pointer to a code object, which is the compiled body with its list of variable names.

This is the same name-and-object model from section 02: price is a label, and the function is the thing the label points to. You can give the label to another name, put the function in a list, or return it from another function.

Defaults are stored on the function too, in __defaults__. That is the same tuple that made codes=[] leak between customers in section 02, and we will lean on it again when we fix the lambda trap.

What you see: the pieces of one function, read off the object itself.

functions_are_objects.py · Python 3.14runs offline
def price(qty, unit=2.5, *, tax=0.2):
    """Price one line."""
    return qty * unit * (1 + tax)

print(type(price), price.__name__, "|", price.__doc__)
print("params     :", price.__code__.co_varnames[:price.__code__.co_argcount])
print("defaults   :", price.__defaults__, price.__kwdefaults__)
price.calls = 0                      # functions accept attributes
price.calls += 1
print("attribute  :", price.calls)

rules = {"flat": lambda q: q * 2.5, "bulk": lambda q: q * 2.0 if q >= 10 else q * 2.5}
for name, fn in rules.items():       # functions as dictionary values
    print(f"{name:5}", fn(12))
output (real run)runs offline
<class 'function'> price | Price one line.
params     : ('qty', 'unit')
defaults   : (2.5,) {'tax': 0.2}
attribute  : 1
flat  30.0
bulk  24.0

Three things in that output matter later. The code object knows its parameter names (co_varnames), the defaults live on the function, and the dictionary of rules shows the everyday payoff: a table of behaviours keyed by name, with no if/elif chain.

That last pattern is how most Python code replaces what a Java developer would write as a switch over an enum or a strategy interface with one class per case.

Bridge: scope, the four places a name is looked up

When Python meets a name inside a function, it searches four places in a fixed order, and stops at the first hit. The order is called LEGB: Local, Enclosing, Global, Built-in.

  1. Local: names the function itself creates, which means its parameters and anything it assigns to.
  2. Enclosing: names in any function this one is nested inside, working outwards.
  3. Global: names at the top level of the module (the file).
  4. Built-in: names Python provides everywhere, such as len, print and ValueError.
Built-in (len, print, ValueError, None) Global (module level: total, price_rules, the def names) Enclosing (an outer function's names, such as seen) Local (parameters and every name this function assigns) x += 1 assigns x, so x is Local for the WHOLE function reading it before the assignment: UnboundLocalError Lookup order: Local, then Enclosing, then Global, then Built-in. First hit wins.
Fig. 19.8 — LEGB. A name is searched from the innermost ring outwards; an assignment anywhere in a function puts that name in the Local ring.

The part that surprises people is the sentence in the picture: an assignment anywhere in a function makes the name local to the whole function. Python decides this once, when it compiles the function, not each time a line runs.

Make the invisible visible: the classic x += 1 failure, and the bytecode (the small instructions Python compiles each function into, explained fully in section 05) that proves the decision was made early.

scope_legb.py · Python 3.14runs offline
import dis

total = 100                      # global

def broken():
    total += 1                   # ❌ TRAP: assignment makes `total` local for the WHOLE function
    return total

def fine():
    print(total + 1)             # only reads: LOAD_GLOBAL

try:
    broken()
except UnboundLocalError as e:
    print("UnboundLocalError:", e)

print("local names of broken:", broken.__code__.co_varnames)
print()
dis.dis(broken)
print()
dis.dis(fine)
output (real run)runs offline
UnboundLocalError: cannot access local variable 'total' where it is not associated with a value
local names of broken: ('total',)

  5           RESUME                   0

  6           LOAD_FAST_CHECK          0 (total)
              LOAD_SMALL_INT           1
              BINARY_OP               13 (+=)
              STORE_FAST               0 (total)

  7           LOAD_FAST_BORROW         0 (total)
              RETURN_VALUE

  9           RESUME                   0

 10           LOAD_GLOBAL              1 (print + NULL)
              LOAD_GLOBAL              2 (total)
              LOAD_SMALL_INT           1
              BINARY_OP                0 (+)
              CALL                     1
              POP_TOP
              LOAD_CONST               1 (None)
              RETURN_VALUE

Why: in broken, the first instruction is LOAD_FAST_CHECK, which means "read a local slot, and complain if it is empty". total += 1 contains an assignment, so the compiler gave total a local slot, and that slot is empty when the line runs. In fine, the same name is only read, so the instruction is LOAD_GLOBAL, which looks in the module.

The fix depends on what you meant. If you wanted to change the module-level name, say so with global. If you wanted to change a name belonging to the function you are nested in, say so with nonlocal.

scope_global_nonlocal.py · Python 3.14runs offline
total = 100

def with_global():
    global total                 # ✅ rebind the module-level name
    total += 1

def outer():
    seen = 0
    def inner():
        nonlocal seen            # ✅ rebind the enclosing function's name
        seen += 1
    inner(); inner()
    return seen

with_global()
print("total:", total, " seen:", outer())
print(len.__module__, "<- built-ins live in the last ring")
output (real run)runs offline
total: 101  seen: 2
builtins <- built-ins live in the last ring

A word of judgement. Needing global in application code is usually a smell, because it makes a function depend on hidden state that tests cannot easily reset. Needing nonlocal is more respectable: it is how a small closure keeps a private counter, which we use in the next section.

The default is simple. Reading outer names always works. Rebinding them needs a declaration. Mutating an object they point to (appending to an outer list) needs nothing, because that is not an assignment to the name.

Bridge: closures, one level down

A closure is a function that keeps using a variable from the function (or loop) where it was written, even after that outer code has finished. The word sounds grand, but the mechanism is small.

When the compiler sees an inner function using an outer name, it stores that name in a little box called a cell. The outer code and the inner function both hold the same cell. A cell holds one reference, and anyone who rebinds the name changes what the cell points to.

You can open the box. Each function has __closure__, a tuple of cells, and each cell has cell_contents. Here are the three handlers from the incident, built with a list comprehension (which has exactly the same trap as the loop), and then a counter that uses nonlocal on purpose.

closure_cells.py · Python 3.14runs offline
tenants = ["acme", "bolt", "crisp"]
handlers = [lambda: tenant for tenant in tenants]   # comprehension, same trap

cells = [h.__closure__[0] for h in handlers]
print("cell objects:", [hex(id(c)) for c in cells])
print("one cell shared:", len({id(c) for c in cells}) == 1)
print("cell_contents:", cells[0].cell_contents)
print("free variable names:", handlers[0].__code__.co_freevars)

def make_counter():
    n = 0
    def bump():
        nonlocal n
        n += 1
        return n
    return bump

c = make_counter()
c(); c()
print("counter cell after 2 calls:", c.__closure__[0].cell_contents)
output (real run)runs offline
cell objects: ['0x75f5cfe95de0', '0x75f5cfe95de0', '0x75f5cfe95de0']
one cell shared: True
cell_contents: crisp
free variable names: ('tenant',)
counter cell after 2 calls: 2

The three id() values are identical. All three lambdas hold one cell, and that cell holds whatever tenant currently is. When the loop ends, tenant is "crisp", so every handler sees "crisp". The counter shows the good use of the same machinery: bump and the outer function share a cell named n, and after two calls it holds 2.

After the loop has finished handler 1: lambda: tenant handler 2: lambda: tenant handler 3: lambda: tenant ONE shared cell for variable "tenant" "acme" "bolt" "crisp" earlier values, now unreachable All three handlers read the same cell, so all three see "crisp". The default-argument fix gives each lambda its own copy of the value instead.
Fig. 19.9 — Late binding. The lambdas captured the variable (one cell), not its value at each pass of the loop.

Java · Spring

A Java lambda may only capture a variable that never changes. The compiler enforces it, so the surprise cannot happen.

Handlers.javaruns offline
for (String tenant : tenants) {
    handlers.add(() -> reprice(tenant));
}
// each pass has its own `tenant`, and it is
// effectively final: changing it is a
// compile error

Python

A Python closure captures the variable itself, and one loop variable is reused on every pass.

handlers.pyruns offline
for tenant in tenants:
    handlers.append(lambda: reprice(tenant))
# ❌ TRAP: one variable for the whole loop,
# read when the lambda is CALLED

The shift: Java captures a value that is frozen by a compiler rule; Python captures a variable and lets you pay the price if it changes.

Idiom: Bind the value when you create the closure

The problem: a function created in a loop (a handler, a callback, a thread target, a deferred task) reads a loop variable that has moved on by the time the function runs.

How it works: make the current value part of the function at the moment you create it, instead of leaving it as a variable to be looked up later. There are three ways, from lightest to heaviest.

  1. Default argument: lambda t=tenant: reprice(t). Defaults are evaluated at creation time (the same __defaults__ rule from section 02), so each lambda gets its own copy.
  2. functools.partial: partial(reprice, tenant) builds a callable that stores the argument inside itself. No lambda, no cell.
  3. Factory function: a small make_handler(tenant) whose parameter is a fresh variable on every call, so each returned lambda has its own cell.
closure_fixes.py · Python 3.14runs offline
from functools import partial

tenants = ["acme", "bolt", "crisp"]

def reprice(tenant):
    return f"repricing {tenant}"

# fix 1: bind the CURRENT value as a default argument
by_default = [lambda t=tenant: reprice(t) for tenant in tenants]
# fix 2: functools.partial stores the value inside the partial object
by_partial = [partial(reprice, tenant) for tenant in tenants]
# fix 3: a factory function gives each handler its own cell
def make_handler(tenant):
    return lambda: reprice(tenant)
by_factory = [make_handler(t) for t in tenants]

for name, hs in [("default arg", by_default), ("partial", by_partial), ("factory", by_factory)]:
    print(f"{name:12}", [h() for h in hs])
output (real run)runs offline
default arg  ['repricing acme', 'repricing bolt', 'repricing crisp']
partial      ['repricing acme', 'repricing bolt', 'repricing crisp']
factory      ['repricing acme', 'repricing bolt', 'repricing crisp']

All three give the right answer. Before the fix, [h() for h in handlers] returned repricing crisp three times, as the first output on this page shows.

Which closure fix to pick
OptionPick it whenCost or catch
Default argument t=tenantA one-line lambda and you want the least code.The function now accepts an extra optional argument; a caller can overwrite it by accident. Fine for private lambdas.
functools.partialYou are binding arguments to an existing named function. It is the clearest to read and picklable.Only for calling a function with fixed arguments; it cannot hold extra logic.
Factory functionThe handler has several lines of logic or its own private state.One more function to write. It is the right choice once the body is not a single expression.

The trap: the same thing happens with for i in range(3): threads.append(Thread(target=lambda: work(i))). The threads start later, and by then i is 2. The cure is identical: Thread(target=work, args=(i,)) passes the value now.

Bridge: decorators, one level down

A decorator is a function that takes a function and returns a function. The @ line is only a shorter way to write the call. These two blocks mean exactly the same thing.

decorator_sugar.py · illustrativeruns offline
# illustrative
@announce
def quote(order_id): ...

# is exactly:
def quote(order_id): ...
quote = announce(quote)      # runs ONCE, when the def statement runs

The second line is the whole secret. The name quote no longer points at your function. It points at whatever announce returned, which is usually a wrapper that calls your function plus some extra work. And that swap happens when the module is imported, not when the function is called.

Make the invisible visible: a decorator that prints when it runs, and a module body that never calls anything.

deco_import_time.py · Python 3.14runs offline
def announce(fn):
    print(f"decorating {fn.__name__} (at definition time)")
    def wrapper(*args, **kwargs):
        print(f"calling {fn.__name__}")
        return fn(*args, **kwargs)
    return wrapper

@announce
def quote(order_id):
    """Return a quote."""
    return f"quote for {order_id}"

print("--- module body finished, nothing called yet ---")
print(quote("o-1"))
print("name:", quote.__name__, "| doc:", quote.__doc__, "| wrapped:", getattr(quote, "__wrapped__", None))
output (real run)runs offline
decorating quote (at definition time)
--- module body finished, nothing called yet ---
calling quote
quote for o-1
name: wrapper | doc: None | wrapped: None

Look at the order. decorating quote appears first, before the "module body finished" line and before any call. And the last line shows the cost: the function's name is now wrapper and its docstring is gone.

Java · Spring

An annotation is passive metadata. A framework reads it later by reflection and decides what to do.

QuoteApi.javaruns offline
@Transactional
public Quote quote(String id) {
    return repo.find(id);
}
// the method body is untouched; Spring
// builds a proxy around the bean later

Python

A decorator is ordinary code. It runs at import time and replaces the function with whatever it returns.

quote_api.pyruns offline
@transactional
def quote(order_id):
    return repo.find(order_id)
# quote is now whatever transactional(quote)
# returned: a different function object

The shift: a Java annotation only describes the method and a framework acts on it; a Python decorator acts, and the name now belongs to its result.

Idiom: Always use functools.wraps in a decorator

The problem: a plain wrapper hides the original function's identity. Its __name__ becomes "wrapper", its docstring disappears, and inspect.signature shows (*args, **kwargs). Routers, loggers, test runners and documentation tools all read those attributes and break or become useless.

How it works: functools.wraps(fn) is itself a decorator that you put on the wrapper. It copies the original's name, docstring, module and annotations onto the wrapper, and sets wrapper.__wrapped__ = fn so tools can find the original.

  1. Write the wrapper: use *args, **kwargs so it accepts any call.
  2. Decorate the wrapper: put @functools.wraps(fn) directly above def wrapper.
  3. Return the wrapper: the caller gets a function that still looks like the original.
deco_wraps.py · Python 3.14runs offline
import functools, inspect

def timed_bad(fn):
    def wrapper(*args, **kwargs):
        return fn(*args, **kwargs)
    return wrapper

def timed_good(fn):
    @functools.wraps(fn)                 # ✅ copies __name__, __doc__, __module__, sets __wrapped__
    def wrapper(*args, **kwargs):
        return fn(*args, **kwargs)
    return wrapper

@timed_bad
def a(order_id: str, qty: int = 1):
    """Price an order."""

@timed_good
def b(order_id: str, qty: int = 1):
    """Price an order."""

for f in (a, b):
    print(f"{f.__name__:8} doc={f.__doc__!r:18} sig={inspect.signature(f)}")
print("b.__wrapped__ is the original:", b.__wrapped__.__name__)
output (real run)runs offline
wrapper  doc=None               sig=(*args, **kwargs)
b        doc='Price an order.'  sig=(order_id: str, qty: int = 1)
b.__wrapped__ is the original: b

The first row is the broken decorator and the second is the fixed one. The second keeps its name, its docstring and, notably, its real signature, because inspect.signature follows __wrapped__ back to the original.

Idiom: A decorator with arguments is three layers

The problem: you want @retry(times=3, backoff=0.1), a decorator with settings. But @something expects something to be a function that takes a function. With parentheses and arguments, what is being applied?

How it works: retry(times=3) is an ordinary call that runs first and returns the real decorator. Python then applies that returned decorator to your function. So you write three nested functions, each with one job.

  1. Outer: takes the settings (times, backoff) and returns the decorator.
  2. Middle: takes the function being decorated and returns the wrapper. This is the plain decorator from before.
  3. Inner: the wrapper that runs on every call, using the settings from the outer layer through closure cells.

The code below retries a flaky rate lookup. To keep the demo fast and exact, the sleep function is a parameter and the demo passes a function that only records the delay. A real service would leave the default time.sleep.

deco_retry.py · Python 3.14runs offline
import functools, time

def retry(times=3, backoff=0.1, exceptions=(Exception,), sleep=time.sleep):
    """Outer layer: takes the settings, returns the real decorator."""
    def decorator(fn):                       # middle layer: takes the function
        @functools.wraps(fn)
        def wrapper(*args, **kwargs):        # inner layer: runs on every call
            delay = backoff
            for attempt in range(1, times + 1):
                try:
                    return fn(*args, **kwargs)
                except exceptions as exc:
                    if attempt == times:
                        raise
                    print(f"  attempt {attempt} failed ({exc}); sleeping {delay:.2f}s")
                    sleep(delay)
                    delay *= 2
        return wrapper
    return decorator

calls = {"n": 0}
slept = []                                   # fake clock: record instead of waiting

@retry(times=4, backoff=0.1, exceptions=(ConnectionError,), sleep=slept.append)
def fetch_rate(currency):
    calls["n"] += 1
    if calls["n"] < 3:
        raise ConnectionError(f"rate service down (call {calls['n']})")
    return f"{currency}=1.08"

print(fetch_rate("EUR"))
print("calls:", calls["n"], "| delays that would have been slept:", slept)

@retry(times=2, exceptions=(ConnectionError,), sleep=slept.append)
def always_fails():
    raise ConnectionError("still down")

try:
    always_fails()
except ConnectionError as e:
    print("gave up:", e)
output (real run)runs offline
  attempt 1 failed (rate service down (call 1)); sleeping 0.10s
  attempt 2 failed (rate service down (call 2)); sleeping 0.20s
EUR=1.08
calls: 3 | delays that would have been slept: [0.1, 0.2]
  attempt 1 failed (still down); sleeping 0.10s
gave up: still down

The first call fails twice, waits 0.1 s then 0.2 s (the delay doubles each time), and succeeds on the third call. The second function never succeeds, so after the last attempt the original exception is re-raised and the caller still sees the real error.

Three details earn their place in review. The wait doubles, which is called exponential backoff, so a struggling service gets breathing room. Only the listed exceptions are retried, so a ValueError from a bug is never repeated three times. And the last failure is re-raised, not swallowed.

Stacked decorators and class-based decorators

You can put several decorators on one function. They are applied from the bottom up (the one closest to def first), but when the function is called, the outermost wrapper runs first. The next demo prints both orders.

deco_stacking.py · Python 3.14runs offline
import functools

def tag(name):
    def deco(fn):
        print(f"apply  {name}")
        @functools.wraps(fn)
        def wrapper(*a, **kw):
            print(f"enter  {name}")
            try:
                return fn(*a, **kw)
            finally:
                print(f"exit   {name}")
        return wrapper
    return deco

@tag("auth")        # outer: applied LAST, runs FIRST
@tag("cache")       # inner: applied FIRST
def handler():
    print("body")

print("--- definition done ---")
handler()
output (real run)runs offline
apply  cache
apply  auth
--- definition done ---
enter  auth
enter  cache
body
exit   cache
exit   auth

Read the output as two separate stories. At definition time, cache was applied first and auth second, so handler = auth(cache(handler)). At call time you walk in through auth, then cache, reach the body, and walk out in reverse.

This is why order matters. If auth is the outer layer, an unauthorised caller is rejected before the cache is even looked at. Swap them and a cached answer could be handed to a caller who should have been refused.

A decorator can also be a class. Python only needs the decorator to be callable, and an instance with a __call__ method is callable. The class form is useful when the decorator needs to keep state that you want to inspect afterwards, such as a call count.

deco_class_based.py · Python 3.14runs offline
import functools

class CountCalls:
    """A class used as a decorator: __init__ gets the function, __call__ runs per call."""
    def __init__(self, fn):
        functools.update_wrapper(self, fn)   # same job as @wraps
        self.fn = fn
        self.calls = 0
    def __call__(self, *args, **kwargs):
        self.calls += 1
        return self.fn(*args, **kwargs)

@CountCalls
def price(qty):
    return qty * 2.5

price(2); price(4)
print(price.__name__, price.calls, type(price).__name__)
output (real run)runs offline
price 2 CountCalls

functools.update_wrapper is what wraps calls underneath; with a class you call it on self. Note that price is now an instance of CountCalls, not a function. That breaks one thing worth knowing: if you decorate a method this way, the instance does not become a bound method, because CountCalls has no __get__. Plain functions get that behaviour for free, which is another reason to prefer function decorators for methods.

Function decorator or class decorator
OptionPick it whenCost or catch
Function decorator with wrapsAlmost always: logging, timing, retry, auth. Works on plain functions and methods.State between calls needs a closure variable or a function attribute.
Class decorator (__call__)You want readable state on the decorator itself (price.calls), or several cooperating methods.Not a function, so no automatic method binding; add __get__ if you decorate methods.
functools.partial or a plain helperYou only need to fix some arguments, not wrap behaviour.No code runs around the call; it is a binding, not a wrapper.

Bridge: generators, one level down

A generator function is any function with yield in its body. Calling it does not run the body. It builds a generator object that holds the function's frame (its local variables and its current position) and hands it back to you.

Each next() call resumes the frame, runs until the next yield, hands that value out, and freezes the frame again. The locals stay alive in between. That is the entire trick, and it is why a generator can produce a million values while holding only one.

The standard library lets you watch the states. inspect.getgeneratorstate reports GEN_CREATED, GEN_RUNNING, GEN_SUSPENDED or GEN_CLOSED, and the frame's f_lasti is the position of the last bytecode instruction that ran.

Make the invisible visible: a countdown generator, watched from outside at every step.

gen_states.py · Python 3.14runs offline
import inspect

def countdown(n):
    print("  body starts")
    while n > 0:
        received = yield n
        print(f"  resumed, received={received!r}")
        n -= 1
    return "done"

g = countdown(2)                                   # nothing printed: the body has not run
print("created   :", inspect.getgeneratorstate(g), "lasti =", g.gi_frame.f_lasti)
print("next ->", next(g))
print("suspended :", inspect.getgeneratorstate(g), "lasti =", g.gi_frame.f_lasti)
print("send  ->", g.send("hello"))
try:
    next(g)
except StopIteration as stop:
    print("StopIteration value:", stop.value)
print("finished  :", inspect.getgeneratorstate(g))
output (real run)runs offline
created   : GEN_CREATED lasti = 2
  body starts
next -> 2
suspended : GEN_SUSPENDED lasti = 46
  resumed, received='hello'
send  -> 1
  resumed, received=None
StopIteration value: done
finished  : GEN_CLOSED

Read it line by line. After countdown(2) nothing is printed, because the body has not started (GEN_CREATED). The first next prints body starts and stops at the yield (GEN_SUSPENDED, with f_lasti now at 46). send("hello") resumes the frame and the yield expression evaluates to "hello".

When the function finishes, Python raises StopIteration, and the generator's return value rides inside it as .value. A for loop hides all this; it simply stops when StopIteration arrives.

Three more methods control a suspended generator from outside. send(x) resumes it and makes the paused yield evaluate to x. throw(exc) raises an exception inside the generator at the paused yield, where it can be caught. close() raises GeneratorExit there so that finally blocks run. Finally, yield from hands control to an inner generator and forwards all three, then gives you the inner generator's return value.

gen_send_throw_close.py · Python 3.14runs offline
def accumulator():
    total = 0
    try:
        while True:
            x = yield total
            total += x
    except ValueError:
        print("  got ValueError inside the generator")
        yield -1
    finally:
        print("  cleanup (finally runs on close)")

g = accumulator()
next(g)                      # prime: run to the first yield
print(g.send(10), g.send(5))
print("throw ->", g.throw(ValueError("bad row")))
g.close()                    # raises GeneratorExit at the paused yield
import inspect; print(inspect.getgeneratorstate(g))

def inner():
    x = yield "a"
    print("  inner got", x)
    return "inner-result"

def outer():
    result = yield from inner()          # delegates send/throw/close, captures return value
    print("  outer got", result)

o = outer()
print(next(o)); 
try: o.send("X")
except StopIteration: pass
output (real run)runs offline
10 15
  got ValueError inside the generator
throw -> -1
  cleanup (finally runs on close)
GEN_CLOSED
a
  inner got X
  outer got inner-result

The accumulator keeps a running total in a local variable, which is state that a plain function could not keep without a class or a global. throw shows that exceptions can be steered into the paused code, and close shows that cleanup runs. The yield from example shows the delegation: outer received inner-result without writing a loop.

Java · Spring

A Stream is lazy until a terminal operation, and it can be consumed once.

Errors.javaruns offline
Map<String, Integer> byTenant =
  lines.stream()
    .map(Row::parse)
    .filter(Row::isError)
    .collect(groupingBy(Row::tenant,
             summingInt(Row::amount)));
// nothing runs until collect()

Python

A generator is lazy and single use too, and it can also pause and receive values.

errors.pyruns offline
rows = parse(lines)         # nothing runs
errs = only_errors(rows)    # nothing runs
totals = total_by_tenant(errs)
# the loop inside the last call
# pulls one row at a time
list(errs)   # [] : already used up

The shift: a Stream is a pipeline object built from operators; a generator is a function whose body is the pipeline stage, and it is also a coroutine that can be suspended from the outside.

Idiom: Process big data as a generator pipeline

The problem: the pricer team reads its order log with f.readlines(), parses every line, then totals the errors. On a laptop with a small file this works. On the production file it holds every line in memory at once, and the container is killed for using too much RAM.

How it works: write each step as a generator that takes an iterable and yields results. Chain them. The file object is itself an iterator over lines, so one line flows through all stages before the next is even read. Memory use is one line, not the whole file.

  1. Parse: a generator turns each text line into a small tuple.
  2. Filter: a generator passes on only the rows you care about.
  3. Aggregate: an ordinary function (not a generator) loops over the last stage and builds the small result.
One item at a time through every stage log file (an iterator) parse() yield tuple only_errors() yield if ERROR total_by_tenant() loop, small dict 1 line 1 row 1 error readlines() list 303.6 MB peak generator pipeline 0.2 MB peak (flat, whatever the file size) Peak memory measured with tracemalloc on a 3,000,000-line, 156 MB log file.
Fig. 19.10 — A generator pipeline moves one item at a time, so memory stays flat. The list version holds every line before it starts.

To measure it we first need a file. The helper below writes a synthetic log of 3,000,000 lines (156 MB on disk) with five tenants and a 2% error rate. The pipeline code follows, with the bad and the good version side by side.

make_log.py · Python 3.14runs offline
import random, sys
path, n = sys.argv[1], int(sys.argv[2])
random.seed(7)
tenants = ["acme", "bolt", "crisp", "dune", "ember"]
with open(path, "w") as f:
    for i in range(n):
        status = "ERROR" if random.random() < 0.02 else "OK"
        f.write(f"2026-11-24T10:{i % 60:02d}:00 {random.choice(tenants)} order={i} amount={random.randint(5, 90)} {status}\n")
gen_pipeline.py · Python 3.14runs offline
import sys, tracemalloc

PATH = sys.argv[1]

def parse(lines):
    for line in lines:
        parts = line.split()
        yield parts[1], int(parts[3].split("=")[1]), parts[4]

def only_errors(rows):
    for tenant, amount, status in rows:
        if status == "ERROR":
            yield tenant, amount

def total_by_tenant(rows):
    out = {}
    for tenant, amount in rows:
        out[tenant] = out.get(tenant, 0) + amount
    return out

def with_list():
    with open(PATH) as f:
        lines = f.readlines()                    # ❌ TRAP: the whole file becomes a list in RAM
    return total_by_tenant(only_errors(parse(lines)))

def with_pipeline():
    with open(PATH) as f:                        # ✅ one line at a time through three stages
        return total_by_tenant(only_errors(parse(f)))

for fn in (with_list, with_pipeline):
    tracemalloc.start()
    result = fn()
    _, peak = tracemalloc.get_traced_memory()
    tracemalloc.stop()
    print(f"{fn.__name__:14} peak = {peak / 1e6:8.1f} MB   {dict(sorted(result.items()))}")

What you see: both functions return the same totals, and the peak memory differs by a factor of about 1,500.

output (real run)runs offline
with_list      peak =    303.6 MB   {'acme': 568869, 'bolt': 571950, 'crisp': 573845, 'dune': 576113, 'ember': 564313}
with_pipeline  peak =      0.2 MB   {'acme': 568869, 'bolt': 571950, 'crisp': 573845, 'dune': 576113, 'ember': 564313}
# measured with tracemalloc on the course machine; your numbers will differ

The totals match to the digit, so the pipeline is not a trick: it computes the same answer. The list version peaked at 303.6 MB for a 156 MB file (each Python string carries about 50 bytes of overhead on top of its characters). The pipeline peaked at 0.2 MB, and that figure would stay the same for a 20 GB file.

Scaling note: we chose 3,000,000 lines to keep the list version under about 600 MB on a 7 GB machine. With 30,000,000 lines the list version would need roughly 3 GB, and the pipeline would still need 0.2 MB.

List comprehension against generator expression

The same idea exists in one line. Square brackets build the whole list right now. Round brackets build a generator that makes each value when asked. Summing ten million doubled numbers shows the cost of each, first with memory measured and then with timing measured separately, because tracemalloc slows everything down.

listcomp_vs_genexp.py · Python 3.14runs offline
import time, tracemalloc

N = 10_000_000

def run(label, make):
    tracemalloc.start()
    t0 = time.perf_counter()
    total = sum(make())
    dt = time.perf_counter() - t0
    _, peak = tracemalloc.get_traced_memory()
    tracemalloc.stop()
    print(f"{label:22} total={total}  peak={peak/1e6:8.1f} MB")
    return dt

def timed(label, make):
    t0 = time.perf_counter(); sum(make()); dt = time.perf_counter() - t0
    print(f"{label:22} {dt:.2f} s")

run("list  [x*2 for ...]", lambda: [x * 2 for x in range(N)])
run("genex (x*2 for ...)", lambda: (x * 2 for x in range(N)))
print("# timing without tracemalloc (it slows everything down)")
timed("list  [x*2 for ...]", lambda: [x * 2 for x in range(N)])
timed("genex (x*2 for ...)", lambda: (x * 2 for x in range(N)))
print("# measured on the course machine; your numbers will differ")
output (real run)runs offline
list  [x*2 for ...]    total=99999990000000  peak=   409.1 MB
genex (x*2 for ...)    total=99999990000000  peak=     0.0 MB
# timing without tracemalloc (it slows everything down)
list  [x*2 for ...]    0.59 s
genex (x*2 for ...)    0.34 s
# measured on the course machine; your numbers will differ

The list needed 409 MB at its peak, because it held ten million integer objects plus the list's own array of pointers. The generator needed essentially nothing. The generator was also faster here (0.34 s against 0.59 s), because allocating and filling a huge list is real work. That time win is not a law: for small inputs, or when you need the list again, the list comprehension is perfectly fine and often a little faster.

A good rule is "if the only thing you will do is loop once, or pass it to sum, any, all, min, max or join, use the generator expression".

itertools in production

The itertools module is a toolbox of lazy building blocks for exactly this style. Five earn their place in service code. islice takes a slice of any iterator without building a list. chain joins iterables end to end. batched (added in 3.12) cuts a stream into fixed-size groups, which is how you send 500 rows at a time to a database. pairwise gives overlapping neighbours, handy for gaps between timestamps. groupby groups consecutive equal keys.

That last word, consecutive, is the trap. groupby does not collect all items with the same key. It starts a new group each time the key changes, exactly like the Unix uniq command. The demo below runs the bug and the fix, and also shows tee.

itertools_demo.py · Python 3.14runs offline
from itertools import islice, chain, batched, pairwise, groupby, tee, count

print("islice  :", list(islice(count(100), 3)))
print("chain   :", list(chain([1, 2], (3,), "ab")))
print("batched :", list(batched(range(7), 3)))
print("pairwise:", list(pairwise([10, 15, 22])))

rows = [("acme", 5), ("bolt", 7), ("acme", 9), ("bolt", 1)]
print("\ngroupby on UNSORTED rows (the bug):")
for key, grp in groupby(rows, key=lambda r: r[0]):
    print(" ", key, [amt for _, amt in grp])

print("groupby after sorting (the fix):")
for key, grp in groupby(sorted(rows), key=lambda r: r[0]):
    print(" ", key, [amt for _, amt in grp])

# tee: the lagging branch forces tee to buffer everything the leader has consumed
a, b = tee(iter(range(5)))
print("\ntee a:", list(a), "then b:", list(b), "(b read from tee's buffer)")
output (real run)runs offline
islice  : [100, 101, 102]
chain   : [1, 2, 3, 'a', 'b']
batched : [(0, 1, 2), (3, 4, 5), (6,)]
pairwise: [(10, 15), (15, 22)]

groupby on UNSORTED rows (the bug):
  acme [5]
  bolt [7]
  acme [9]
  bolt [1]
groupby after sorting (the fix):
  acme [5, 9]
  bolt [1, 7]

tee a: [0, 1, 2, 3, 4] then b: [0, 1, 2, 3, 4] (b read from tee's buffer)

On unsorted rows, acme appears twice as two separate groups, and so does bolt. A report built on that would print each tenant twice with partial totals. Sorting first (or using a dictionary) fixes it. If the data is too big to sort in memory, that is a signal to let the database do the grouping.

Finally, tee splits one iterator into several independent ones, but it must remember every item the fastest branch has consumed that the slowest has not. If one branch reads everything before the other starts, tee quietly stores the whole stream. Use it only when the branches advance together.

functools: five tools, one real use each

The functools module holds helpers that treat functions as values. Five of them show up in real services, and one of those five has a famous memory trap.

functools_demo.py · Python 3.14runs offline
from functools import cache, lru_cache, partial, singledispatch, reduce, cached_property

@lru_cache(maxsize=2)
def rate(currency):
    print(f"  computing {currency}")
    return {"EUR": 1.08, "GBP": 1.27, "JPY": 0.0067}[currency]

for c in ["EUR", "EUR", "GBP", "JPY", "EUR"]:
    rate(c)
print(rate.cache_info())          # hits, misses, maxsize, currsize

@singledispatch
def render(x): return f"obj {x!r}"
@render.register
def _(x: int): return f"int {x}"
@render.register
def _(x: list): return f"list of {len(x)}"
print(render(3), "|", render([1, 2]), "|", render("s"))

double = partial(pow, 2)          # pow(2, n)
print("partial:", double(10), "| reduce:", reduce(lambda a, b: a * b, [1, 2, 3, 4]))

class Report:
    @cached_property
    def heavy(self):
        print("  computing heavy once")
        return 42
r = Report(); r.heavy; r.heavy
print("cached in instance dict:", "heavy" in r.__dict__)
output (real run)runs offline
  computing EUR
  computing GBP
  computing JPY
  computing EUR
CacheInfo(hits=1, misses=4, maxsize=2, currsize=2)
int 3 | list of 2 | obj 's'
partial: 1024 | reduce: 24
  computing heavy once
cached in instance dict: True

Walk through the cache output. With maxsize=2, the sequence EUR, EUR, GBP, JPY, EUR computes EUR (miss), serves EUR from the cache (hit), computes GBP (miss), computes JPY (miss, evicting the least recently used, which is EUR), and then must compute EUR again (miss). That is 1 hit and 4 misses, and cache_info() reports exactly that: hits=1, misses=4, currsize=2.

That read-out is how you choose maxsize. Run the real traffic, look at the hit ratio, and raise the size only while the hits keep climbing. A cache with a 5% hit rate is not saving you anything and is costing memory.

Idiom: Bound your caches, and never cache a method on self

The problem: @lru_cache on a method looks harmless. But the cache is one dictionary shared by the whole class, and its key includes self. So the cache holds a strong reference to every instance that ever called the method. Those instances are never freed, even after you delete them. With maxsize=None the cache also never evicts, so the leak is unlimited.

How it works: make sure the thing stored as a cache key is plain data (a string, a number, a tuple) and that the cache has a bound. Three ways to do it.

  1. Cache a module-level function: take the data as arguments (rate_for("EUR")), not the object.
  2. Make the cache per instance: build lru_cache inside __init__ so it lives and dies with the object.
  3. Use cached_property: for a value with no arguments, the result is stored on the instance itself and freed with it.

Make the invisible visible: we create an object, call the cached method, delete the object, force a collection, and ask a weak reference (a pointer that does not keep its target alive, from section 02) whether the object is still there.

cache_method_leak.py · Python 3.14runs offline
import functools, gc, weakref

class Pricer:
    @functools.lru_cache(maxsize=None)           # ❌ TRAP: the cache key includes `self`
    def rate(self, currency):
        return 1.08

p = Pricer()
p.rate("EUR")
probe = weakref.ref(p)
del p
gc.collect()
print("after del + gc, Pricer still alive:", probe() is not None)
print("cache_info:", Pricer.rate.cache_info())

class Pricer2:
    def __init__(self):
        self._rate = functools.lru_cache(maxsize=128)(self._rate_uncached)   # ✅ per-instance cache
    def _rate_uncached(self, currency):
        return 1.08
    def rate(self, c): return self._rate(c)

q = Pricer2(); q.rate("EUR")
probe2 = weakref.ref(q)
del q
gc.collect()
print("per-instance cache, still alive:", probe2() is not None)

@functools.cache                                  # ✅ module-level function: key is plain data
def rate_for(currency):
    return 1.08
print("module-level cache keyed by str:", rate_for("EUR"), rate_for.cache_info().currsize)
output (real run)runs offline
after del + gc, Pricer still alive: True
cache_info: CacheInfo(hits=0, misses=1, maxsize=None, currsize=1)
per-instance cache, still alive: False
module-level cache keyed by str: 1.08 1

Why: after del p and gc.collect(), the first Pricer is still alive, because the class-level cache holds self as part of the key. The per-instance version is gone, and the module-level function caches only the string "EUR".

Which cache to use
OptionPick it whenCost or catch
@cache on a module-level functionThe arguments are small and the set of possible values is small and fixed (currency codes, tenant ids).Unbounded. If arguments are user input, memory grows without limit.
@lru_cache(maxsize=N) on a module-level functionArguments are plain data and the set is open-ended. Pick N from the measured hit ratio.Holds N results in memory; keys must be hashable; results must not be mutated.
Per-instance lru_cache built in __init__The cached result depends on the object's own settings.Creates a reference cycle (object, cache, bound method), so it is freed by the cycle collector, not at once.
@cached_propertyOne computed value per object, no arguments.Never refreshes unless you delete the attribute. Needs a normal __dict__ (not with plain __slots__).
External cache (Redis)Many processes need the same cached value, or it must survive a restart or have a time-to-live.A network call, and you must design how stale entries are invalidated.

That completes the toolbox for functions. Closures and decorators change how a function is built; generators change how it runs; the cache decorators change how often it runs. All three are possible because a function in Python is an object you can wrap, suspend and remember. Next, the layer underneath all of it: what the interpreter really does with your code.

05 · ExecutionHow CPython Runs Your Code: Bytecode, the GIL and Imports

CPython, the standard Python, does not run your text directly. It compiles each file to bytecode, small instructions that a loop executes one by one, and it protects its own internals with one global lock. Knowing those two facts explains why threads do not speed up pure Python, why the same code gets faster after warm-up, and why a module's top-level code runs exactly once.

Back to the Black Friday incident from section 01. The pricer team has 400,000 orders to price, and the rules are pure Python arithmetic. A developer reads that "threads make things run at the same time", wraps the work in a ThreadPoolExecutor(4), and ships it. The nightly job gets slower.

The reason is not a mistake in the pool. It is one lock inside the interpreter. To see exactly what it does, we ran the same job on the normal Python 3.14 and on the free-threaded build, 3.14t, which has no such lock. The work is always split into four equal chunks; only the number of worker threads changes.

The setup: a CPU-bound function standing in for the price rules, and a pool that runs four chunks of 100,000 orders. Each timing is the best of three runs on the course machine, which has 12 cores, so four threads always have a core each.

gil_threads.py · Python 3.14 and 3.14truns offline
import sys, time
from concurrent.futures import ThreadPoolExecutor

ORDERS = 400_000

def price_rules(order_id):
    """CPU-bound stand-in for the pricing rules: pure Python arithmetic."""
    total = 0
    for k in range(25):
        total += (order_id * k) % 7 + (order_id ^ k) % 5
    return total

def price_chunk(bounds):
    lo, hi = bounds
    return sum(price_rules(i) for i in range(lo, hi))

def run(workers):
    step = ORDERS // 4                       # always 4 equal chunks; only the pool size changes
    chunks = [(i * step, (i + 1) * step) for i in range(4)]
    t0 = time.perf_counter()
    with ThreadPoolExecutor(workers) as pool:
        result = sum(pool.map(price_chunk, chunks))
    return time.perf_counter() - t0, result

gil = getattr(sys, "_is_gil_enabled", lambda: True)()
print(f"Python {sys.version.split()[0]}  GIL enabled: {gil}")
for workers in (1, 4):
    best = min(run(workers)[0] for _ in range(3))
    print(f"  {workers} thread(s): {best:6.2f} s for {ORDERS:,} orders (best of 3)")

Make the invisible visible: the same script, run by two different interpreters.

output (real runs)runs offline
$ python3.14 gil_threads.py
Python 3.14.7  GIL enabled: True
  1 thread(s):   0.70 s for 400,000 orders (best of 3)
  4 thread(s):   1.04 s for 400,000 orders (best of 3)
$ python3.14t gil_threads.py
Python 3.14.7  GIL enabled: False
  1 thread(s):   0.84 s for 400,000 orders (best of 3)
  4 thread(s):   0.25 s for 400,000 orders (best of 3)
# measured on the course machine (12 cores); your numbers will differ
400,000 orders, pure-Python rules, best of 3 (seconds)
Interpreter1 thread4 threadsWhat happened
Python 3.14 (GIL on)0.701.044 threads were about 49% slower than 1
Python 3.14t (GIL off)0.840.254 threads were 3.4 times faster than 1

Two readings matter. On the normal build, four threads are slower than one, because the threads take turns on a single lock and pay for the switching. On the free-threaded build, four threads really run at once and the job finishes in about a third of the time.

But look at the left column too. One thread on 3.14t took 0.84 s against 0.70 s on 3.14. We measured that gap separately, with a plain loop and no pool, twice each, taking the best of five runs every time.

single-thread cost of free-threadingruns offline
Python 3.14.7 GIL=True: one thread, 400,000 orders, best of 5 = 0.684 s
Python 3.14.7 GIL=False: one thread, 400,000 orders, best of 5 = 0.842 s
Python 3.14.7 GIL=True: one thread, 400,000 orders, best of 5 = 0.678 s
Python 3.14.7 GIL=False: one thread, 400,000 orders, best of 5 = 0.832 s
# 0.678 s -> 0.832 s and 0.684 s -> 0.842 s: about 23% slower on one thread
# measured on the course machine; your numbers will differ

So the free-threaded build was about 23% slower with a single thread in this test. That cost buys the ability to scale across cores. Whether it is worth paying depends on how parallel your workload is, and we come back to that decision at the end of the free-threading discussion.

Now the mechanism, in the order the interpreter meets your code: compile first, then execute, and then the lock that sits around execution.

Bridge: from source text to running code

When you run python app.py, CPython does not interpret the characters one at a time. It runs a small compiler pipeline first.

  1. Tokens: the text is cut into words and symbols (total, =, price, *, qty).
  2. AST: the tokens are arranged into a tree that shows the structure of the code. This is the abstract syntax tree. Linters and tools like pytest's assertion rewriting work on this tree.
  3. Bytecode: the tree is turned into a flat list of tiny instructions for a stack machine (an imaginary computer that works by pushing and popping values on a stack).
  4. Eval loop: a big C loop reads each instruction and does what it says. Every Python line you run is going through this loop.
What happens to one .py file source text price * qty tokens NAME * NAME AST (tree) ast.dump() bytecode dis.dis() eval loop runs each one compile: once per file, when it is imported run: every call __pycache__/ app.cpython-314.pyc saved after the first compile next run: load it, skip compiling The .pyc is reused only while the source's modification time and size (or a hash) still match.
Fig. 19.11 — From source to running code. Compilation is done once per file and cached as a .pyc; only the eval loop runs on every call.

You can look at the middle stages yourself. ast.dump prints the tree and dis prints the bytecode. Here is a three-line function, pulled apart.

ast_dis.py · Python 3.14runs offline
import ast, dis

source = '''def line_total(price, qty):
    total = price * qty
    return total
'''
tree = ast.parse(source)
print(ast.dump(tree.body[0].body[0], indent=2))
print()
code = compile(source, "<pricer>", "exec")
dis.dis(code.co_consts[0])
print("\nraw bytes of the function body:", code.co_consts[0].co_code.hex(" "))
output (real run)runs offline
Assign(
  targets=[
    Name(id='total', ctx=Store())],
  value=BinOp(
    left=Name(id='price', ctx=Load()),
    op=Mult(),
    right=Name(id='qty', ctx=Load())))

  1           RESUME                   0

  2           LOAD_FAST_BORROW_LOAD_FAST_BORROW 1 (price, qty)
              BINARY_OP                5 (*)
              STORE_FAST               2 (total)

  3           LOAD_FAST_BORROW         2 (total)
              RETURN_VALUE

raw bytes of the function body: 80 00 57 01 2c 05 00 00 00 00 00 00 00 00 00 00 70 02 56 02 23 00

Read the tree first: an Assign whose value is a BinOp that multiplies two Names. That is total = price * qty as structure. Then the bytecode. LOAD_FAST_BORROW_LOAD_FAST_BORROW pushes both local variables on the stack (the interpreter fuses two loads into one instruction), BINARY_OP pops them and pushes the product, and STORE_FAST pops the result into total. The numbers in the left margin are source line numbers.

The exact instruction names change between versions; this output is from 3.14.7. The raw bytes at the bottom are the same program as numbers, two bytes per instruction plus empty slots that the interpreter later fills with cached information. That brings us to the second trick.

Bridge: the specialising interpreter, why code speeds up after warm-up

Python is dynamic: in price * qty the two values could be integers, floats, strings or your own class. So a generic BINARY_OP must check the types every time before it knows what to do.

Since Python 3.11 (PEP 659) the interpreter learns from what it sees. After a function has run a few times, each instruction that keeps meeting the same types is rewritten in place into a faster, specialised version that assumes those types and checks only cheaply that the assumption still holds. This is sometimes called quickening: the instruction quietly becomes quick once it has seen enough calls. The Python team reports speed-ups of 10 to 60% over 3.10, about 25% on average.

The dis module can show the specialised form with adaptive=True. We look at the same instruction before any call, after 1,000 calls with integers, and after floats are mixed in.

adaptive_dis.py · Python 3.14runs offline
import dis

def line_total(price, qty):
    return price * qty

def show(title):
    print(title)
    for ins in dis.get_instructions(line_total, adaptive=True):
        if ins.opname.startswith("BINARY_OP"):
            print("   ", ins.opname, "|", ins.argrepr)

show("before any call:")
for _ in range(1000):
    line_total(3, 4)
show("after 1,000 calls with ints:")
for _ in range(1000):
    line_total(1.5, 2.5)
line_total(3, 4)
show("after floats were mixed in:")
output (real run)runs offline
before any call:
    BINARY_OP | *
after 1,000 calls with ints:
    BINARY_OP_MULTIPLY_INT | *
after floats were mixed in:
    BINARY_OP_MULTIPLY_FLOAT | *

Before any call, the instruction is the generic BINARY_OP. After 1,000 integer calls it has become BINARY_OP_MULTIPLY_INT, which skips the type dispatch. When floats arrive, the integer guess fails, the interpreter falls back to the generic path, and after enough float calls it re-specialises to BINARY_OP_MULTIPLY_FLOAT.

Two practical lessons follow. Benchmarks need a warm-up, because the first calls are slower than the hundredth. And code that always sees the same types in a given place runs faster than code that sees five different types there, which is one reason a function called with "mostly ints, sometimes strings" is slower than it looks.

Bridge: frames, the recursion limit and zero-cost exceptions

Each function call creates a frame: a record that holds the function's local variables and its place in the bytecode. Frames are stacked as calls nest. Python caps the stack depth with the recursion limit, 1,000 by default, so that a runaway recursion raises RecursionError instead of crashing the whole process by exhausting memory.

Python also does not do tail-call optimisation (reusing the frame when a function's last act is to call itself). The reason Guido van Rossum gave is that it would erase frames from tracebacks, and readable tracebacks matter more to the language than deep recursion. Write a loop or use an explicit stack instead.

Exceptions are cheap when they do not happen. Since 3.11, a try block adds no instructions to the normal path. Instead the compiler writes a side table, the exception table, that maps ranges of instructions to handlers, and the interpreter consults it only when an exception is actually raised.

recursion_exc_table.py · Python 3.14runs offline
import dis, sys

print("recursion limit:", sys.getrecursionlimit())
def down(n):
    return down(n + 1)
depth = []
def probe(n=0):
    depth.append(n)
    probe(n + 1)
try:
    probe()
except RecursionError as e:
    print("RecursionError after", len(depth), "calls:", e)

def parse(text):
    try:
        return int(text)
    except ValueError:
        return 0
print()
dis.dis(parse)
output (real run)runs offline
recursion limit: 1000
RecursionError after 999 calls: maximum recursion depth exceeded

  15           RESUME                   0

  16           NOP

  17   L1:     LOAD_GLOBAL              1 (int + NULL)
               LOAD_FAST_BORROW         0 (text)
               CALL                     1
       L2:     RETURN_VALUE

  --   L3:     PUSH_EXC_INFO

  18           LOAD_GLOBAL              2 (ValueError)
               CHECK_EXC_MATCH
               POP_JUMP_IF_FALSE        5 (to L5)
               NOT_TAKEN
               POP_TOP

  19   L4:     POP_EXCEPT
               LOAD_SMALL_INT           0
               RETURN_VALUE

  18   L5:     RERAISE                  0

  --   L6:     COPY                     3
               POP_EXCEPT
               RERAISE                  1
ExceptionTable:
  L1 to L2 -> L3 [0]
  L3 to L4 -> L6 [1] lasti
  L5 to L6 -> L6 [1] lasti

The first two lines show the limit (1,000) and that the probe died after 999 calls. In the dis output, the lines labelled L1 to L2 are the body of the try: just LOAD_GLOBAL, LOAD_FAST_BORROW and CALL. The try: line itself compiled to a NOP, which does nothing. The handler code lives after the RETURN_VALUE, and the ExceptionTable: at the bottom says "if an exception happens between L1 and L2, jump to L3". On the happy path the handler costs nothing.

It is also worth knowing that raising and catching an exception is not cheap. The zero-cost promise is only for the case where nothing is raised, so using exceptions for ordinary control flow in a hot loop is still slower than an if.

Bridge: the GIL, one level down

The GIL (global interpreter lock) is a single lock inside CPython. A thread must hold it to run Python bytecode. So at any instant, only one thread in a process is executing Python, no matter how many cores the machine has.

What does it protect? Not your data. It protects the interpreter's own internals, above all the reference counts from section 02 (the number stored in every object that says how many names point to it). Two threads updating one count at the same moment could corrupt it and free an object that is still in use. One big lock made that impossible without a lock on every object, which was a simple and fast design for single-threaded code.

The lock is not held forever. A thread gives it up in two situations.

  1. On a timer: a thread that has run for the switch interval, 0.005 s (5 ms) by default, is asked to hand over, and another waiting thread takes the lock.
  2. When it blocks: time.sleep, waiting for a socket or file, lock.acquire, and many C extensions (hashing big buffers, compression, numpy's heavy loops) release the lock while they work in C, because they are not touching Python objects.
Three threads, one GIL: one runs Python at a time thread 1 thread 2 thread 3 I/O, GIL free at most 5 ms time holds the GIL, runs Python waits for the GIL blocked on I/O, lock released
Fig. 19.12 — The GIL timeline. The lock changes hands every few milliseconds or when a thread blocks; while thread 1 waits on I/O, threads 2 and 3 use the free lock.

This picture predicts three results, and a single script can check all three. It runs four tasks of each kind with one worker and with four. Waiting and big C calls should speed up. Pure Python should not.

gil_release.py · Python 3.14runs offline
import hashlib, sys, time
from concurrent.futures import ThreadPoolExecutor

def run(label, fn, n_items, workers):
    t0 = time.perf_counter()
    with ThreadPoolExecutor(workers) as pool:
        list(pool.map(fn, range(n_items)))
    return time.perf_counter() - t0

blob = b"x" * 100_000_000          # 100 MB

def wait(_): time.sleep(0.5)       # blocking wait: releases the GIL
def digest(_): hashlib.sha256(blob).hexdigest()   # big C call: releases the GIL
def spin(_):                       # pure Python: holds the GIL
    t = 0
    for i in range(3_000_000): t += i % 7

print(f"Python {sys.version.split()[0]}  GIL enabled: {sys._is_gil_enabled()}")
for name, fn in [("time.sleep(0.5) x4", wait), ("sha256 of 100 MB x4", digest), ("pure Python loop x4", spin)]:
    one = run(name, fn, 4, 1)
    four = run(name, fn, 4, 4)
    print(f"  {name:22} 1 worker: {one:5.2f} s   4 workers: {four:5.2f} s")
output (real run)runs offline
Python 3.14.7  GIL enabled: True
  time.sleep(0.5) x4     1 worker:  2.00 s   4 workers:  0.50 s
  sha256 of 100 MB x4    1 worker:  0.22 s   4 workers:  0.06 s
  pure Python loop x4    1 worker:  0.43 s   4 workers:  0.96 s
# measured on the course machine (12 cores); your numbers will differ

The sleeps overlap perfectly: 2.00 s of waiting becomes 0.50 s, because a sleeping thread does not hold the lock. The SHA-256 of 100 MB, four times, sped up about 3.7 times, because hashlib releases the lock while it hashes. The pure Python loop got worse, 0.43 s to 0.96 s: the threads take turns, and the hand-over costs time.

That is the whole rule behind "threads help I/O but not CPU". It is not about threads being weak. It is about whether the thread is holding the lock while it works.

Does the GIL make counter += 1 safe?

This is a favourite interview question, and the honest answer has two halves. The GIL stops the interpreter from corrupting itself. It does not stop your data from being wrong, because counter += 1 is not one step. Here is its bytecode.

dis_increment.py · Python 3.14runs offline
import dis
counter = 0
def bump():
    global counter
    counter += 1
dis.dis(bump)
output (real run)runs offline
  3           RESUME                   0

  5           LOAD_GLOBAL              0 (counter)
              LOAD_SMALL_INT           1
              BINARY_OP               13 (+=)
              STORE_GLOBAL             0 (counter)
              LOAD_CONST               1 (None)
              RETURN_VALUE

Four steps: read counter, add 1, BINARY_OP, then write it back with STORE_GLOBAL. If a thread is paused after the read and another thread changes the value, the first thread later writes back a stale number, and the other thread's update is lost. The GIL decides when a switch can happen, and it can happen between those instructions.

So we ran the race: four threads, each adding 1 a million times, on a shared global. The right answer is 4,000,000. First on normal 3.14, then on the free-threaded build.

gil_race.py · Python 3.14 and 3.14truns offline
import sys, threading

counter = 0
PER_THREAD = 1_000_000

def bump():
    global counter
    for _ in range(PER_THREAD):
        counter += 1                 # ❌ TRAP: read, add, write are separate steps

def run_once():
    global counter
    counter = 0
    threads = [threading.Thread(target=bump) for _ in range(4)]
    for t in threads: t.start()
    for t in threads: t.join()
    return counter

gil = getattr(sys, "_is_gil_enabled", lambda: True)()
print(f"Python {sys.version.split()[0]}  GIL enabled: {gil}  expected = {4 * PER_THREAD:,}")
for attempt in range(1, 6):
    got = run_once()
    print(f"  run {attempt}: counter = {got:,}  lost = {4 * PER_THREAD - got:,}")
output (real runs)runs offline
$ python3.14 gil_race.py
Python 3.14.7  GIL enabled: True  expected = 4,000,000
  run 1: counter = 4,000,000  lost = 0
  run 2: counter = 4,000,000  lost = 0
  run 3: counter = 4,000,000  lost = 0
  run 4: counter = 4,000,000  lost = 0
  run 5: counter = 4,000,000  lost = 0
$ python3.14t gil_race.py
Python 3.14.7  GIL enabled: False  expected = 4,000,000
  run 1: counter = 1,092,983  lost = 2,907,017
  run 2: counter = 1,074,268  lost = 2,925,732
  run 3: counter = 1,178,337  lost = 2,821,663
  run 4: counter = 1,045,915  lost = 2,954,085
  run 5: counter = 1,165,216  lost = 2,834,784

On the normal build, five runs in a row gave exactly 4,000,000. No updates were lost. That does not mean the code is safe. In this version of the interpreter, a thread is only asked to give up the lock at a few safe points (such as the backward jump at the end of a loop), and in this short loop body the switch never happened to land inside the read-then-write window. The result depends on version and luck.

On the free-threaded build, every run lost about 2.9 million of the 4 million updates. Four threads really did run at the same moment and overwrote each other's results, so only about a quarter of the increments survived.

To prove the code was never safe, we can widen the window on the normal build. A time.sleep(0) between the read and the write stands in for any real operation that releases the lock, such as a log call, a network call or a C extension. The locked version wraps the same three lines in a threading.Lock.

gil_race_widened.py · Python 3.14runs offline
import sys, threading, time

counter = 0
lock = threading.Lock()
PER_THREAD = 20_000

def bump_unsafe():
    global counter
    for _ in range(PER_THREAD):
        tmp = counter                # read
        time.sleep(0)                # any GIL release (I/O, sleep, a C call) can land here
        counter = tmp + 1            # write back a stale value

def bump_locked():
    global counter
    for _ in range(PER_THREAD):
        with lock:                   # ✅ the invariant "read-modify-write is one step" is ours to protect
            tmp = counter
            time.sleep(0)
            counter = tmp + 1

def run(target):
    global counter
    counter = 0
    ts = [threading.Thread(target=target) for _ in range(4)]
    for t in ts: t.start()
    for t in ts: t.join()
    return counter

print(f"Python {sys.version.split()[0]}  GIL enabled: {sys._is_gil_enabled()}  expected = {4 * PER_THREAD:,}")
print(f"  unsafe : {run(bump_unsafe):,}")
print(f"  locked : {run(bump_locked):,}")
output (real run)runs offline
Python 3.14.7  GIL enabled: True  expected = 80,000
  unsafe : 20,005
  locked : 80,000

Even with the GIL on, the unsafe version produced 20,005 instead of 80,000. The locked version produced exactly 80,000. The lesson is the sentence interviewers want: the GIL protects the interpreter, not your invariants. A read-modify-write on shared data needs a Lock (or a queue.Queue, or a design with no shared mutable state), on every build of Python.

Free-threaded Python: no GIL, a cost, and a decision

A free-threaded build of CPython runs without the GIL, so threads can use several cores for real. Its history is short. Python 3.13 added it as experimental (PEP 703). Python 3.14 made it officially supported (PEP 779), but it is still a separate build, python3.14t, not the default interpreter. You can ask any interpreter which kind it is.

which build am I running?runs offline
$ python3.14 gil_facts.py
version            : 3.14.7
switch interval    : 0.005 seconds
GIL enabled        : True
Py_GIL_DISABLED    : 0
$ python3.14t gil_facts.py
version            : 3.14.7
switch interval    : 0.005 seconds
GIL enabled        : False
Py_GIL_DISABLED    : 1
Three threads, no GIL: truly parallel thread 1 thread 2 thread 3 runs Python on core 1 runs Python on core 2 runs Python on core 3 all three finish here time Same work under the GIL: three bars end to end, about 3 times as long. cost: a small lock per object and slower single-thread code
Fig. 19.13 — Without the GIL, the three threads of Fig. 19.12 run side by side. Safety now rests on per-object locks inside the interpreter, which is where the extra cost comes from.

What does it cost? We measured it above. On a pure-Python loop, one thread was about 23% slower on 3.14t than on 3.14, and four threads were 3.4 times faster than one. Other costs are worth knowing, and we state these without numbers because we did not measure them.

The interpreter needs per-object locking and a different memory-management scheme for reference counts. Native extension modules written for the old model must be updated; the free-threaded interpreter will switch the GIL back on if it loads an extension that has not declared itself safe (check the notes for your Python version and the extensions you use).

Ways to use more than one core for CPU-bound Python
OptionPick it whenCost or catch
Threads on free-threaded 3.14tShared in-memory data, fine-grained work, and all your dependencies work on the free-threaded build.About 23% slower single thread in our test; you must lock shared data yourself; some wheels may be missing.
Processes (ProcessPoolExecutor)Big independent units of work. It works on any normal build today.Each process has its own memory; arguments and results are copied by pickling (section 06).
Subinterpreters (3.14)Isolation like processes with lower start-up cost, in one process.Objects are not shared; the ecosystem is still young (section 06).
Native code (numpy, Rust, Cython)The hot loop is numeric and can leave Python entirely.A second language or a library, but the largest speed-ups (see vectorising, below).

A sensible evaluation plan is short. Pick the one CPU-heavy job. Run it on 3.14 and 3.14t with the same code. Check that every dependency imports on 3.14t without silently turning the GIL back on (sys._is_gil_enabled() should print False after all imports).

Compare the single-thread and the multi-thread numbers against your real core count. Run your tests several times, because races that were hiding behind the GIL (like the counter above) become visible. Adopt it only for the services where the multi-thread gain is larger than the single-thread loss.

The experimental JIT: measure, do not assume

A JIT (just-in-time compiler) turns frequently used bytecode into machine code while the program runs. CPython 3.13 added an experimental one, built on a "copy-and-patch" technique (PEP 744). It is off by default. On the interpreters we have, it is compiled in, and the PYTHON_JIT=1 environment variable switches it on.

is the JIT on?runs offline
$ python3.14 jit_status.py
Python 3.14.7
JIT compiled in : True
JIT enabled now : False
JIT running now : False
$ PYTHON_JIT=1 python3.14 jit_status.py | tail -3
JIT compiled in : True
JIT enabled now : True
JIT running now : False

Does it help? We timed the same single-thread pricing loop with the JIT off and on, on 3.14 and on the 3.15 release candidate.

single-thread pricing loop, JIT off and onruns offline
PYTHON_JIT=0  Python 3.14.7 GIL=True best of 5 = 0.677 s
PYTHON_JIT=1  Python 3.14.7 GIL=True best of 5 = 0.817 s
PYTHON_JIT=0  Python 3.15.0rc1 GIL=True best of 5 = 0.645 s
PYTHON_JIT=1  Python 3.15.0rc1 GIL=True best of 5 = 0.622 s
# measured on the course machine; your numbers will differ

On 3.14 the JIT made this loop about 21% slower (0.677 s to 0.817 s). On 3.15.0rc1 it was about 4% faster (0.645 s to 0.622 s). The Python team reports an average gain of about 7 to 8% on x86-64 Linux across a standard benchmark suite, so a few percent on one loop is in the same range.

The sensible reading is the one the Python developers give: it is improving, it is still experimental, and the only way to know is to run your own workload both ways before turning it on.

Bridge: the import system, one level down

An import statement is a function call in disguise, and it does the following. First Python looks the module's name up in sys.modules, a dictionary of every module already loaded. If it is there, you get that object back immediately and nothing runs. If it is not, finders search for the file, a loader reads and compiles it (using the .pyc cache from Fig. 19.11), the module object is put in sys.modules before its code runs, and then the module's top-level code runs, once.

That last detail, "put in the cache before running", is the root of the circular-import problem a little further down. First, the basic behaviour, shown with a tiny module that prints when its body runs, and a package whose __init__.py also prints.

rates.py · Python 3.14runs offline
print("  rates.py body is running")
RATE = 1.08
run_imports.py · Python 3.14runs offline
import sys
print("first import:")
import rates
print("second import (same name, anywhere):")
import rates as again
print("same object:", rates is again, "| in sys.modules:", "rates" in sys.modules)
print("rates.__spec__.loader:", type(rates.__spec__.loader).__name__)
print("rates.__cached__ :", rates.__cached__.split("/")[-2:])

print("\nimport pricer_pkg.tax:")
import pricer_pkg.tax
print("name bound here:", [n for n in dir() if n.startswith("pricer")])
print("both cached:", "pricer_pkg" in sys.modules, "pricer_pkg.tax" in sys.modules)
output (real run)runs offline
first import:
  rates.py body is running
second import (same name, anywhere):
same object: True | in sys.modules: True
rates.__spec__.loader: SourceFileLoader
rates.__cached__ : ['__pycache__', 'rates.cpython-314.pyc']

import pricer_pkg.tax:
  pricer_pkg/__init__.py runs
  pricer_pkg/tax.py runs
name bound here: ['pricer_pkg']
both cached: True True

Three facts are on show. The module body printed once, on the first import; the second import printed nothing and returned the same object. The loader was SourceFileLoader and the compiled copy lives in __pycache__. And import pricer_pkg.tax ran the package's __init__.py first, then tax.py, and bound only the top name pricer_pkg in the importing file; you reach tax as pricer_pkg.tax.

Circular imports: the half-built module

Now the incident that shows up only after a refactor. The pricer has two modules. service.py needs the list of rules from rules.py, and rules.py wants the tax_rate function from service.py. Each imports the other. Run the service and this is what you get.

cycle/service.py · Python 3.14runs offline
from rules import RULES          # needs rules to be fully loaded

def price(order):
    return sum(rule(order) for rule in RULES)

def tax_rate():
    return 0.2
cycle/rules.py · Python 3.14runs offline
from service import tax_rate     # ❌ TRAP: service is still half-loaded when this line runs

RULES = [lambda order: order * (1 + tax_rate())]
output of main.py (real run)runs offline
# paths shortened
Traceback (most recent call last):
  File "main.py", line 1, in <module>
    import service
  File "service.py", line 1, in <module>
    from rules import RULES          # needs rules to be fully loaded
    ^^^^^^^^^^^^^^^^^^^^^^^
  File "rules.py", line 1, in <module>
    from service import tax_rate     # ❌ TRAP: service is still half-loaded when this line runs
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ImportError: cannot import name 'tax_rate' from 'service' (consider renaming 'cycle/service.py' if it has the same name as a library you intended to import)

Follow the sequence in the figure below. main.py imports service. Python registers service in sys.modules and starts running its first line, which imports rules. Python registers rules and starts running its first line, which asks service for tax_rate. But service is still on its first line, stuck waiting for rules, so the def tax_rate further down has never run. The name does not exist yet, and Python raises ImportError.

main.py service.py rules.py 1 import service 2 from rules import RULES 3 from service import tax_rate service is in sys.modules, but tax_rate is not defined yet 4 ImportError travels back up through every importer to main.py
Fig. 19.14 — The circular import. Each module is registered before its body finishes, so the second import sees a half-built module that has not defined its names yet.

The wording of the message depends on the version and on how the program is started. The same two files, run on Python 3.12, give the classic text.

the same files on Python 3.12 (real run)runs offline
# paths shortened
ImportError: cannot import name 'tax_rate' from partially initialized module 'service' (most likely due to a circular import) (cycle/service.py)

On 3.12 the message says "partially initialized module ... (most likely due to a circular import)". On 3.14, when the script is started from the folder that holds the modules, we saw "consider renaming" instead, which is a hint for a different bug (your file shadowing a library).

Both mean the same thing here. Run the same files so that the folder is not the script folder (for example, add it to sys.path from another directory) and 3.14 also prints "partially initialized". Do not rely on the exact wording in a log search.

Idiom: Break import cycles, do not work around them

The problem: two modules import names from each other at the top. It works until one import order changes, then fails with an ImportError that points at a line that looks innocent. A circular import is almost always a sign that two modules share a responsibility that belongs in a third place.

How it works: remove the cycle by choosing one of three fixes, in this order of preference.

  1. Restructure: move the shared piece (here tax_rate) into a third module that both import. The dependency now points one way only.
  2. Import the module, not the name: import rules and then write rules.RULES inside functions. The lookup of RULES happens at call time, after both modules have finished loading.
  3. Import inside the function: a local from rules import RULES inside price() runs only when called. It hides the cycle rather than removing it, so use it for a cycle you cannot restructure yet.
cycle_fixed/rates.py · Python 3.14runs offline
def tax_rate():                  # ✅ shared piece moved into a third module
    return 0.2
cycle_fixed/rules.py · Python 3.14runs offline
from rates import tax_rate

RULES = [lambda order: order * (1 + tax_rate())]
cycle_fixed/service.py · Python 3.14runs offline
import rules                     # ✅ import the module object; look names up at call time

def price(order):
    return sum(rule(order) for rule in rules.RULES)
output of main.py (real run)runs offline
12.0

With tax_rate in rates.py, the chain is service to rules to rates, one direction, and price(10) returns 12.0 (10 plus 20% tax). A third variant, kept in the code folder as service_lazy_variant.py, shows the function-level import.

Slow start-up: find it with -X importtime

Every import runs the module's top-level code, so many imports mean a slow start. A command-line tool that takes 1.8 seconds to print --help is nearly always paying for imports it does not need yet. The interpreter will tell you where the time goes: -X importtime prints one line per module, on stderr, with the time in microseconds.

cli_imports.py · Python 3.14runs offline
import json, decimal, argparse, sqlite3, http.client

print("loaded")
the five slowest imports (real run)runs offline
$ python3.14 -X importtime cli_imports.py 2>&1 >/dev/null | sort -t'|' -k2 -n -r | head
import time: self [us] | cumulative | imported package
import time:      7948 |      51090 | http.client
import time:      1126 |      28013 |   email.parser
import time:      2983 |      25831 |     email.feedparser
import time:     20715 |      24727 | argparse
import time:      1817 |      21753 |       email._policybase
import time:      3292 |      11044 |         email.header
import time:      6938 |       9052 |   email.message
import time:      2757 |       8894 |         email.utils
# self = time in that module alone, cumulative = including what it imported
# measured on the course machine; your numbers will differ

The column that finds the culprit is cumulative. http.client costs 51 ms in total, and most of that is the email package it pulls in. argparse costs 25 ms. A tool that only needs those modules in one rare sub-command pays the price on every run. Ten such modules is how you reach seconds.

Three remedies exist. Import the heavy module inside the function that needs it (fine for a CLI, with the caveat above). Split the program so that the fast path does not import the slow one. Or, in Python 3.15, use an explicit lazy import.

Idiom: Lazy imports (Python 3.15, PEP 810)

The problem: a module imports ten libraries at the top, but a given run uses two of them. The other eight cost start-up time for nothing. A function-level import fixes the time but scatters imports through the file and hides the module's real dependencies.

How it works: Python 3.15 added a keyword. lazy import json binds the name json to a small placeholder, a lazy_import object, without loading the module. The first time you use the name (json.dumps), Python loads the real module, replaces the placeholder in your namespace, and carries on.

  1. Declare: write lazy import x or lazy from x import y at the top of the file, exactly where the normal import would go.
  2. Use as normal: nothing else in the code changes.
  3. Pay on first use: the cost moves to the first call that touches the name; if that call never happens, the module is never loaded.
lazy_import_demo.py · Python 3.15.0rc1runs offline
import sys
lazy import json                      # PEP 810: nothing is loaded yet

print("json in sys.modules right after the lazy import:", "json" in sys.modules)
print("type of the name `json`:", type(globals()["json"]).__name__)
print("first use:", json.dumps({"ok": True}))
print("json in sys.modules after first use:", "json" in sys.modules)
print("type of the name `json` now:", type(json).__name__)
output (real run)runs offline
json in sys.modules right after the lazy import: False
type of the name `json`: lazy_import
first use: {"ok": true}
json in sys.modules after first use: True
type of the name `json` now: module

Before first use, json is not in sys.modules and the name's type is lazy_import. After json.dumps, the module is loaded and the name is a normal module. The same works for from imports.

lazy_from.py · Python 3.15.0rc1runs offline
import sys
lazy from decimal import Decimal      # lazy form of "from ... import ..."
print("decimal loaded before use:", "decimal" in sys.modules)
print(Decimal("0.1") + Decimal("0.2"))
print("decimal loaded after use :", "decimal" in sys.modules)
output (real run)runs offline
decimal loaded before use: False
0.3
decimal loaded after use : True

There are rules, enforced by the compiler. A lazy import is allowed only at module level. Inside a function, a class body or a try/except block it is a SyntaxError.

the two forbidden places (real runs)runs offline
$ python3.15 lazy_import_rules.py
  File "lazy_import_rules.py", line 2
    lazy import json                  # ❌ not allowed inside a function
    ^^^^^^^^^^^^^^^^
SyntaxError: lazy import not allowed inside functions
$ python3.15 lazy_import_rules2.py
  File "lazy_import_rules2.py", line 2
    lazy import json                  # ❌ not allowed inside try/except
    ^^^^^^^^^^^^^^^^
SyntaxError: lazy import not allowed inside try/except blocks

There is also a global switch for existing code. Starting the interpreter with -X lazy_imports=all, or setting the PYTHON_LAZY_IMPORTS environment variable, makes ordinary imports lazy without editing files. On this release candidate both worked.

the global switch (real run)runs offline
$ python3.15 lazy_global_switch.py
json loaded at startup: True
$ python3.15 -X lazy_imports=all lazy_global_switch.py
json loaded at startup: False
$ PYTHON_LAZY_IMPORTS=all python3.15 lazy_global_switch.py
json loaded at startup: False

Finally the effect on start-up. We imported four modules (argparse, sqlite3, http.client, decimal) eagerly and lazily, three times each. The very first line is a cold run, where Python also had to compile the modules to .pyc files.

output (real run)runs offline
eager: imports took 120.7 ms
lazy: imports took 0.0 ms
eager: imports took 22.5 ms
lazy: imports took 0.0 ms
eager: imports took 19.8 ms
lazy: imports took 0.0 ms
# measured on the course machine; your numbers will differ

The lazy imports took effectively zero time, against about 20 ms warm and 120 ms cold for the eager version. The time did not vanish. It moves to the first use of each module, so the tool is faster to start and pays only for what a given run needs.

Ways to avoid paying for an import you may not use
OptionPick it whenCost or catch
lazy import x (3.15)You can require Python 3.15, and the module is used on only some paths.Module scope only. Import side effects (registering plugins) now happen later. Errors in the module surface at first use.
Import inside the functionYou must support older Pythons, or the cycle cannot be fixed yet.Imports scattered in the file; a small cost per call; errors surface mid-request.
Split into sub-commands or modulesThe slow part is a big, clearly separate feature.More structure to design.
Eager import (the default)A long-running server where start-up happens once. You want import errors at boot, not at the first request.Start-up time is paid every time the process starts.

Bridge: if __name__ == "__main__" and process start methods

Every module has a built-in variable __name__. When you run a file directly (python app.py), Python sets it to the string "__main__". When the same file is imported by another one, __name__ is the module's name instead. So if __name__ == "__main__": means "only when I am the program, not when I am being imported".

Usually this is a convenience, so that importing a file in a test does not start the server. With multiprocessing it becomes essential, because of how new worker processes start. There are three start methods. fork copies the running process. spawn starts a fresh interpreter and re-imports your main file to find the worker function. forkserver asks a small helper server process to start the workers. We can check which one is the default.

start_methods.py · Python 3.12, 3.14 and 3.15runs offline
import multiprocessing as mp, sys
print(f"Python {sys.version.split()[0]} on Linux: default start method = {mp.get_start_method()}")
output (real runs)runs offline
Python 3.12.3 on Linux: default start method = fork
Python 3.14.7 on Linux: default start method = forkserver
Python 3.15.0rc1 on Linux: default start method = forkserver

On Linux the default changed. 3.12 used fork; 3.14 uses forkserver, and so does 3.15.0rc1. macOS and Windows already used spawn. Both spawn and forkserver re-import your main file inside every worker, and that is where the guard matters.

Idiom: Guard process creation with if __name__ == "__main__"

The problem: a script creates a process pool at the top level, with no guard. Under spawn, each worker re-imports the file, hits the same top-level lines and tries to create its own pool. Python detects that and refuses, and the whole job dies with a confusing traceback. On Linux with the old fork default you might never have seen it, and then it appears when someone runs the code on a Mac or on 3.14.

How it works: put everything that should happen only once, in the real program, under the guard. Workers import the file with __name__ set to "__mp_main__", so the guarded block is skipped and they just get the function definitions.

  1. Keep definitions at the top level: functions and classes that workers need must be importable.
  2. Put the launch under the guard: creating the pool and calling map belong in if __name__ == "__main__":.
  3. No work at import time: do not start threads, processes or servers just by importing.
mainguard/no_guard.py · Python 3.14runs offline
from concurrent.futures import ProcessPoolExecutor
import multiprocessing as mp

def price(order):
    return order * 2

ctx = mp.get_context("spawn")                # the default on macOS and Windows; 3.14 Linux uses forkserver
with ProcessPoolExecutor(2, mp_context=ctx) as pool:    # ❌ TRAP: no `if __name__ == "__main__"` guard
    print(list(pool.map(price, range(4))))
output (real run, shortened)runs offline
Traceback (most recent call last):   # in a worker process
  ...
    raise RuntimeError('''
    ...<16 lines>...
    ''')
RuntimeError:
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...

        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.

        To fix this issue, refer to the "Safe importing of main module"
        section in https://docs.python.org/3/library/multiprocessing.html
  ...
Traceback (most recent call last):
  File "no_guard.py", line 9, in <module>
  ...
concurrent.futures.process.BrokenProcessPool: A process in the process pool was terminated abruptly while the future was running or pending.

That is the failure: "An attempt has been made to start a new process before the current process has finished its bootstrapping phase". The worker re-imported the file, reached the pool line, and Python stopped it. The parent then reports BrokenProcessPool. Now the guarded version, and the default 3.14 method with a print that shows the re-import.

mainguard/with_guard.py · Python 3.14runs offline
from concurrent.futures import ProcessPoolExecutor
import multiprocessing as mp

def price(order):
    return order * 2

if __name__ == "__main__":                   # ✅ children import this file but skip this block
    ctx = mp.get_context("spawn")
    with ProcessPoolExecutor(2, mp_context=ctx) as pool:
        print(list(pool.map(price, range(4))))
output (real run)runs offline
[0, 2, 4, 6]
mainguard/guard_forkserver.py · Python 3.14runs offline
from concurrent.futures import ProcessPoolExecutor

def price(order):
    return order * 2

print("module body running, __name__ =", __name__)    # shows the re-import in each worker
if __name__ == "__main__":
    with ProcessPoolExecutor(2) as pool:              # default method on 3.14: forkserver
        print(list(pool.map(price, range(4))))
output (real run)runs offline
module body running, __name__ = __main__
module body running, __name__ = __mp_main__
[0, 2, 4, 6]

With the guard the job returns [0, 2, 4, 6]. In the second script, the print line appears twice: once as __main__ in the parent, and once as __mp_main__ in a worker. That second line is the proof that the worker re-ran the top of the file, and why anything outside the guard runs again in each worker.

When the hot loop is numeric, take it out of Python

Everything in this section so far explains why plain Python loops are slow: every + goes through the eval loop, every number is an object with a reference count. If the loop is numeric, the best speed-up is to stop running it in Python at all.

Idiom: Vectorise the hot loop

The problem: the pricer applies a tax and a fee to five million prices. A for loop does it, one Python object at a time, and the profile says this loop is the whole run time.

How it works: hand the whole array to code written in C that loops over raw numbers with no per-item objects. In pure Python you can sometimes use a built-in (sum, map, bytes methods) that does the loop in C. For real numeric work, use numpy.

  1. Find the loop: profile first (section 07); do not guess.
  2. Keep data in one typed array: a numpy array holds raw numbers side by side, not 5 million separate objects.
  3. Express the rule on the whole array: arr * 1.2 + 0.5 instead of a loop.
vectorise_hot_loop.py · Python 3.12 with numpy 2.5runs offline
import time
import numpy as np

N = 5_000_000
prices = [float(i % 90 + 5) for i in range(N)]
arr = np.array(prices)

def timed(label, fn):
    t0 = time.perf_counter(); r = fn(); dt = time.perf_counter() - t0
    print(f"{label:34} {dt * 1000:8.1f} ms   result={r:,.1f}")

def python_loop():
    total = 0.0
    for p in prices:
        total += p * 1.2 + 0.5            # price with 20% tax and 0.50 fee
    return total

timed("python for-loop", python_loop)
timed("sum(generator expression)", lambda: sum(p * 1.2 + 0.5 for p in prices))
timed("sum(list) * 1.2 + 0.5 * N (algebra)", lambda: sum(prices) * 1.2 + 0.5 * N)
timed("numpy: (arr * 1.2 + 0.5).sum()", lambda: (arr * 1.2 + 0.5).sum())

# a heavier per-item rule: surge multiplier = sqrt(price^2 + 4)
import math
timed("python loop with math.sqrt", lambda: sum(math.sqrt(p * p + 4.0) for p in prices))
timed("numpy: np.sqrt(arr * arr + 4).sum()", lambda: np.sqrt(arr * arr + 4.0).sum())
output (real run)runs offline
python for-loop                       147.3 ms   result=299,498,800.0
sum(generator expression)             169.0 ms   result=299,498,800.0
sum(list) * 1.2 + 0.5 * N (algebra)     34.0 ms   result=299,498,800.0
numpy: (arr * 1.2 + 0.5).sum()         23.5 ms   result=299,498,800.0
python loop with math.sqrt            277.2 ms   result=247,834,472.2
numpy: np.sqrt(arr * arr + 4).sum()     36.3 ms   result=247,834,472.2
# measured on the course machine; your numbers will differ

Read the results carefully, because they are less dramatic than some blog posts. The plain loop took 147 ms. Wrapping the same arithmetic in a generator expression inside sum was a little slower, 169 ms. Using algebra to move the constants out of the loop (sum(prices) * 1.2 + 0.5 * N) took 34 ms, because sum runs in C, but that trick only works when the formula is that simple. Numpy took 23.5 ms.

The second case has a heavier formula, a square root per item. The Python loop took 277 ms and numpy 36 ms, about 7.6 times faster. The more arithmetic per item, the more the object-free loop wins. For small lists, the cost of converting to an array can eat the gain, so measure with your real sizes.

Speeding up a numeric hot loop
OptionPick it whenCost or catch
Built-ins (sum, map, min) or algebraThe rule is simple and no new dependency is acceptable.Limited to what the built-ins can express.
numpy arraysMany numbers, the same rule applied to all of them.New dependency; data must be in arrays; awkward for branching per item.
numba, Cython, Rust (PyO3)The loop has real logic per item that numpy cannot express.Compilation step or a second language (compared in section 07).
More cores (processes, 3.14t)The work is already efficient but there is a lot of it.Multiplies by cores at best; it does not fix a slow inner loop.

That closes the execution layer. A line of Python is tokenised, parsed, compiled to bytecode and run by a loop that specialises as it learns. A lock around that loop decides what threads can do, and the import system decides when your top-level code runs. The next section builds on exactly this: how to choose between threads, processes and asyncio when you now know what each one can and cannot do.

06 · ConcurrencyThreads, Processes, asyncio and Subinterpreters — Choosing the Model

Python gives you five ways to do more than one thing at a time: threads, processes, asyncio, subinterpreters and free-threaded threads. They differ in what they share, what they cost, and what they are good for. This section runs each one, measures it, and ends with a rule for choosing.

Here is an incident from pricer, the service that prices food orders for QuickBite. The team moves the price endpoint to an async web framework, because they expect thousands of customers to be waiting on slow tax and promotion lookups at the same time.

A developer writes the new handler as async def price(request). Inside it, one line calls the tax service with a normal blocking HTTP client. It looks harmless, it passes review, and in a test with one request it works.

On launch day there are 50 customers at once. Before the change, p99 latency (the time that 99 out of 100 requests beat) was about 0.1 seconds. After it, p99 is about 5 seconds, and the CPU is almost idle. Nothing is slow. Everything is standing in a line behind one call.

The cause is that an async program has one thread and one loop, and a blocking call freezes the loop for everyone. You can reproduce it without any network, by pretending each call takes 100 milliseconds.

The setup: 50 coroutines, each making a "100 ms call". We run the same 50 calls three ways and time the whole batch each time.

blocking_in_async.py · Python 3.14runs offline
import asyncio
import time

CALLS = 50


async def good():
    await asyncio.sleep(0.1)            # hands control back to the loop


async def bad():
    time.sleep(0.1)                     # ❌ TRAP: blocks the whole loop


async def threaded():
    await asyncio.to_thread(time.sleep, 0.1)   # ✅ runs in a worker thread


async def timed(name, fn):
    t0 = time.perf_counter()
    await asyncio.gather(*(fn() for _ in range(CALLS)))
    print(f"{name:<34}{time.perf_counter() - t0:6.2f} s")


async def main():
    print(f"{CALLS} requests, each one a '100 ms call'")
    await timed("await asyncio.sleep(0.1)", good)
    await timed("time.sleep(0.1) inside async def", bad)
    await timed("await asyncio.to_thread(time.sleep)", threaded)


asyncio.run(main())

Make the invisible visible: the measured totals.

output · Python 3.14.7runs offline
# measured on the course machine (12 cores); your numbers will differ
50 requests, each one a '100 ms call'
await asyncio.sleep(0.1)            0.10 s
time.sleep(0.1) inside async def    5.01 s
await asyncio.to_thread(time.sleep)  0.40 s
Fifty "100 ms calls" in one asyncio program, three ways (measured)
How the call is madeTotal for 50 callsWhat the p99 customer feels
await asyncio.sleep(0.1)0.10 sAll 50 waits overlap, so everyone waits one call's time.
time.sleep(0.1) inside async def5.01 sThe loop is frozen during each call, so call number 50 starts 4.9 s late.
await asyncio.to_thread(time.sleep, 0.1)0.41 sFifty calls over 16 worker threads: ceil(50 / 16) = 4 rounds of 0.1 s.

The first row is what async promises. The second row is the incident: 50 × 0.1 s = 5.0 s, plus a little overhead. The loop did not get slower. It simply could not run anything else while the call held it.

The third row is the honest middle. Moving the blocking call to a thread fixes the freeze, but it does not give you 0.10 s. The default thread pool has min(32, cpu_count + 4) workers. On this 12-core machine that is 16 (we print it in a later demo), so 50 calls need four rounds. That is why the result is 0.41 s and not 0.10 s.

Why: await means "I am waiting, run someone else now". A plain time.sleep or a blocking HTTP call never says that. It keeps the one thread and gives nothing back until it returns.

Bridge: five ways to run things at once

Before the event loop, step back and see the whole map. Python has five concurrency models, and a senior engineer should be able to say what each one shares, what it is for, and what it costs.

Two words first. Concurrency means several tasks are in progress in the same period, even if only one is running at any instant. Parallelism means several tasks are literally running at the same instant on different CPU cores. Waiting on the network needs concurrency. Crunching numbers needs parallelism.

The five concurrency models in Python 3.14, side by side
ModelWhat the workers shareBest forCost or catch
Threads (threading, ThreadPoolExecutor)Everything: one process, one memory.Waiting on blocking libraries: HTTP clients, database drivers, files.On the standard build the GIL lets one thread run Python at a time, so CPU-bound work gets no faster. Shared memory needs locks.
Processes (multiprocessing, ProcessPoolExecutor)Nothing. Data is copied between them (pickled).CPU-bound work on any Python version.Start-up time, memory per process, and the cost of copying arguments and results.
asyncioEverything, in one thread with one loop.Thousands of simultaneous waits with async libraries.One blocking call stalls all tasks. Every layer must be async (function colouring).
Subinterpreters (concurrent.interpreters, 3.14)Nothing by default. Each has its own objects and its own GIL.CPU-bound pure-Python tasks that you want cheaper than processes.New and young. Data still has to be copied or shared through special channels. Not every C extension supports it.
Free-threaded threads (python3.14t)Everything, with no GIL.CPU-bound work that wants shared memory and real parallelism.A separate build. Slower single-thread speed (Section 05 measures it). Races you never saw with the GIL can now appear.

Notice the pattern in the second column. As you move down the table you trade shared memory for safety, or the other way round. Threads and asyncio share everything, so they are cheap and easy to wire up but easy to corrupt. Processes and subinterpreters share nothing, so they are safe but you pay to copy data.

Fig. 19.15 turns that table into a decision you can make in about thirty seconds.

Choosing a concurrency model What is the work mostly doing? Waiting: network, disk, database Computing: your own Python code Async libraries, thousands of waits? Is the inner loop plain numbers or bytes? yes no yes no no asyncio one loop, many waits threads to_thread, pool native code numpy, Cython, Rust processes any version, safest 3.14t threads or interpreters Measure before you pick: the right leaf depends on task size and library support.
Fig. 19.15 — Choosing a model: first ask whether the work is waiting or computing. Waiting leads to asyncio or threads, computing leads to native code first, then processes, free-threaded threads or subinterpreters.

Read the tree from the top. If the program mostly waits, the question is only whether your libraries are async. If they are, asyncio gives the best use of one thread. If they are blocking, threads are the simplest fix, and asyncio.to_thread lets the two meet.

If the program mostly computes, ask first whether the hot loop is plain numbers. If it is, push it into native code, as Section 05 shows with numpy. Only when it is real Python logic do you reach for processes, the free-threaded build, or subinterpreters.

Bridge: the event loop, one level down

To see why one blocking call is so harmful, you need to know what the loop actually does. The vocabulary is small. A coroutine is a function defined with async def. A task is a coroutine that has been handed to the loop to run. The event loop is a plain while loop in one thread that runs tasks, one step at a time.

Calling an async def function does not run it. It builds a coroutine object, a paused function that has not started. Here is that, and the classic mistake that comes with it.

coroutine_object.py · Python 3.14runs offline
import asyncio


async def price(order_id):
    print("body running for", order_id)
    return order_id * 100


coro = price(7)                      # nothing printed: the body has not started
print(type(coro).__name__, coro.cr_frame.f_lasti, coro.cr_running)
print("result:", asyncio.run(coro))  # the loop drives it to the end


async def forgotten():
    price(8)                         # ❌ TRAP: no await, the body never runs


asyncio.run(forgotten())
output · Python 3.14.7runs offline
coroutine 2 False
body running for 7
result: 700
/home/iam100god/Desktop/AI_COURSE/code/e19-python-deep-dive/C/coroutine_object.py:15: RuntimeWarning: coroutine 'price' was never awaited
  price(8)                         # ❌ TRAP: no await, the body never runs
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

Read the first line of output. Right after the call, the body had not printed anything, and cr_frame.f_lasti was still at the very start of the function. The body ran only when asyncio.run drove it. In the last function, the call was never awaited, so the body never ran at all, and Python could only warn you after the fact.

Now the loop itself. It owns two things: a ready queue (tasks that can run right now) and a selector (the operating system's way of watching many sockets and timers at once, called epoll on Linux). Fig. 19.16 shows how they connect.

One asyncio event loop, one level down ready queue task A task B task C event loop (one thread) 2 runs one task step until it awaits selector (epoll) sockets and timers that are being waited on 1 pop 3 wait 4 ready 5 back in line await asyncio.sleep(0.1): the 50 waits overlap all 50 waits = 0.10 s time.sleep(0.1) inside async def: the loop is frozen, 50 calls in a row = 5.01 s measured Same scale in both rows: 100 px = 0.1 s. Each tick is one call during which nothing else can be popped from the queue.
Fig. 19.16 — The loop pops a task, runs it until its next await, parks the wait in the selector and moves on. A blocking call never reaches the await, so the loop cannot move on; fifty of them in a row take fifty times as long.

The loop repeats five steps, forever.

  1. Pop: take the first task from the ready queue.
  2. Run until it awaits: the task runs ordinary Python code until it reaches an await on something that is not finished yet. At that point it hands control back.
  3. Register the wait: the thing being awaited (a socket read, a timer) is registered with the selector, which watches it for the operating system.
  4. Ask the selector: when the queue is empty, the loop asks the selector which waits are done. If none are, it sleeps in the operating system at no CPU cost.
  5. Back in line: every task whose wait finished goes to the back of the ready queue, and the loop starts again at step 1.

Step 2 is the whole contract. A task keeps the thread until it says await. There is no timer that interrupts it, and no other thread that could run in its place. This is called cooperative scheduling: the tasks must cooperate by yielding.

Compare this with threads, where the operating system can pause one thread at any moment and run another. That is preemptive scheduling. It is safer against a task that forgets to yield, and more dangerous for shared data, because a switch can land between any two lines.

The setup: two polite tenants that each wait 0.1 s, and one "hog" that blocks for 0.3 s. All three start together.

loop_one_level_down.py · Python 3.14runs offline
import asyncio
import time


async def tenant(name, pause):
    print(f"{name}: start")
    await asyncio.sleep(pause)         # suspend: the loop runs someone else
    print(f"{name}: resumed")


async def hog():
    print("hog: start (blocking 0.3 s, nobody else can run)")
    time.sleep(0.3)
    print("hog: done")


async def main():
    t0 = time.perf_counter()
    a = asyncio.create_task(tenant("A", 0.1))
    b = asyncio.create_task(tenant("B", 0.1))
    h = asyncio.create_task(hog())
    await asyncio.gather(a, b, h)
    print(f"total {time.perf_counter() - t0:.2f} s; A and B wanted 0.1 s each")


asyncio.run(main())

What you see:

output · Python 3.14.7runs offline
A: start
B: start
hog: start (blocking 0.3 s, nobody else can run)
hog: done
A: resumed
B: resumed
total 0.30 s; A and B wanted 0.1 s each

Look at the order. Tasks A and B printed "start", then the hog took the thread. During the hog's 0.3 s, A's 0.1 s timer expired, but A could not be resumed, because the loop was busy inside the hog. A and B resumed only after the hog finished. They wanted 0.1 s; they got 0.3 s. That is exactly the 50-customer incident on a smaller scale.

Bridge: asking the loop who is hogging it

In production you do not know which line blocks. asyncio has a debug mode that watches every step of every task and warns when one takes too long. You switch it on with asyncio.run(main(), debug=True), or with the environment variable PYTHONASYNCIODEBUG=1. The limit is loop.slow_callback_duration, 0.1 seconds by default.

slow_callback_debug.py · Python 3.14runs offline
import asyncio
import time


async def handler():
    time.sleep(0.2)          # blocking call hidden inside a coroutine


async def main():
    loop = asyncio.get_running_loop()
    loop.slow_callback_duration = 0.05      # warn above 50 ms
    await handler()


asyncio.run(main(), debug=True)
output · Python 3.14.7runs offline
Executing <Task finished name='Task-1' coro=<main() done, defined at /home/iam100god/Desktop/AI_COURSE/code/e19-python-deep-dive/C/slow_callback_debug.py:9> result=None created at /home/iam100god/.local/share/uv/python/cpython-3.14.7-linux-x86_64-gnu/lib/python3.14/asyncio/runners.py:110> took 0.200 seconds

The message names the task and says it "took 0.200 seconds". It does not point at the exact line, but it names the coroutine (main()) that held the loop. From there you search that coroutine's body for synchronous calls.

Debug mode is slow and noisy, so it belongs in staging or in a one-off investigation, not in production. For production, the cheaper signal is the one the incident gave you: p99 latency rising while CPU stays low. In Python 3.14 you can also look inside a running program with python -m asyncio ps <pid> and python -m asyncio pstree <pid>, which print every task and what it is awaiting.

Idiom: Move blocking calls out with to_thread

The problem: you must call something that blocks (a synchronous HTTP client, a database driver, a file read, a heavy parse) from inside async def. Called directly, it freezes the loop for every other request.

How it works: asyncio.to_thread(fn, *args) runs fn in a worker thread from the loop's default thread pool and returns an awaitable. The loop stays free while the thread blocks.

  1. Wrap the call: result = await asyncio.to_thread(blocking_fn, arg). It copies the current context variables into the thread (the next idioms use this).
  2. Size the pool: the default pool has min(32, cpu_count + 4) threads. For heavier use, create your own ThreadPoolExecutor and use loop.run_in_executor(pool, fn, arg).
  3. Prefer a real async library when one exists: a thread costs memory and a context switch, an async client costs neither.
to_thread_vs_executor.py · Python 3.14runs offline
import asyncio
import time


def blocking_lookup(sku):
    time.sleep(0.1)                     # stands in for requests.get / a DB driver
    return f"price-for-{sku}"


async def main():
    loop = asyncio.get_running_loop()
    a = await asyncio.to_thread(blocking_lookup, "pizza")
    b = await loop.run_in_executor(None, blocking_lookup, "fries")
    print(a, b)
    print("default executor workers:", loop._default_executor._max_workers)


asyncio.run(main())
output · Python 3.14.7runs offline
price-for-pizza price-for-fries
default executor workers: 16

Bridge: calling async from sync, and sync from async

The two worlds meet in two directions. From synchronous code you start the loop once, at the top of the program, with asyncio.run(main()). From async code you call blocking code with to_thread, as above.

The mistake is mixing them: a synchronous helper that was called from a coroutine tries to start its own loop with asyncio.run. A loop is already running in this thread, and Python refuses.

run_inside_loop.py · Python 3.14runs offline
import asyncio


async def tax_for(region):
    await asyncio.sleep(0.01)
    return 0.19


def sync_helper():
    # ❌ TRAP: a sync function that is called from async code and tries to start its own loop
    return asyncio.run(tax_for("DE"))


async def handler():
    return sync_helper()


print("from sync code:", asyncio.run(tax_for("DE")))
try:
    asyncio.run(handler())
except RuntimeError as e:
    print("RuntimeError:", e)
output · Python 3.14.7runs offline
from sync code: 0.19
RuntimeError: asyncio.run() cannot be called from a running event loop
<sys>:0: RuntimeWarning: coroutine 'tax_for' was never awaited
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

The error text is clear. The warning at the bottom is the same never-awaited coroutine you saw earlier: the helper created tax_for("DE") and then asyncio.run refused to run it. The fix is not to nest loops. Make the helper async and await it, or, if it must stay synchronous, call it from async code through to_thread.

A rule of thumb: asyncio.run appears once in a program, in the entry point (or in a test). If you find it deep inside a library function, that is a bug waiting to happen.

Java · virtual threads

Write plain blocking code. The JVM parks the virtual thread at a blocking call and runs another one. No special keywords.

Pricer.javaruns offline
try (var ex = Executors
        .newVirtualThreadPerTaskExecutor()) {
  for (var o : orders) {
    ex.submit(() -> {
      var tax = http.send(req);   // blocks
      return price(o, tax);       // fine
    });
  }
}

Python · asyncio

Every function on the path must be async, and one blocking call stalls all tasks.

price.py · Python 3.14runs offline
async def price(o, client):
    tax = await client.get(url)   # async
    return compute(o, tax)

async def main(orders, client):
    async with asyncio.TaskGroup() as tg:
        for o in orders:
            tg.create_task(price(o, client))

The shift: Java hides the waiting inside the runtime, so old blocking code just works. Python makes waiting visible in the type of every function (async versus plain), so you gain control and lose compatibility with blocking libraries. This is called "function colouring": an async function can only be awaited from another async function.

Both designs are good answers to the same question, "how do I serve thousands of waiting clients with few threads?" Java answers at the runtime level. Python answers in the language. The Python price is the colouring problem, and to_thread is the bridge between the colours. Chapter E2 covers the JVM side.

Bridge: gather versus TaskGroup, and what "structured" means

Pricer's price endpoint needs three things for every order: the tax rate, the active promotions, and the delivery fee. They are independent, so the handler runs them at the same time. The question is what should happen when one of them fails.

The older tool is asyncio.gather(a, b, c). The newer one, since Python 3.11, is asyncio.TaskGroup. The difference is not speed. It is what happens to the other tasks when one raises.

The setup: three tasks. Task a fails after 0.10 s, task b would finish at 0.30 s, task c at 0.50 s. We run the trio under gather and then under a TaskGroup, with a clock printed on every line.

gather_vs_taskgroup.py · Python 3.14runs offline
import asyncio
import time

T0 = time.perf_counter()


def log(msg):
    print(f"t={time.perf_counter() - T0:4.2f}  {msg}")


async def price(name, delay, fail=False):
    try:
        await asyncio.sleep(delay)
        if fail:
            raise ValueError(f"{name} failed")
        log(f"{name} finished")
        return name
    except asyncio.CancelledError:
        log(f"{name} was CANCELLED")
        raise


async def with_gather():
    print("--- gather ---")
    try:
        await asyncio.gather(price("a", 0.1, fail=True), price("b", 0.3), price("c", 0.5))
    except ValueError as e:
        log(f"gather raised: {e}  (siblings still running)")
    await asyncio.sleep(0.6)
    log("end of gather demo")


async def with_taskgroup():
    print("--- TaskGroup ---")
    try:
        async with asyncio.TaskGroup() as tg:
            tg.create_task(price("a", 0.1, fail=True))
            tg.create_task(price("b", 0.3))
            tg.create_task(price("c", 0.5))
    except* ValueError as eg:
        log(f"except* caught {len(eg.exceptions)} error: {eg.exceptions[0]}")
    log("end of TaskGroup demo")


async def main():
    await with_gather()
    global T0
    T0 = time.perf_counter()
    await with_taskgroup()


asyncio.run(main())

Make the invisible visible: who is still running after the failure.

output · Python 3.14.7runs offline
--- gather ---
t=0.10  gather raised: a failed  (siblings still running)
t=0.30  b finished
t=0.50  c finished
t=0.70  end of gather demo
--- TaskGroup ---
t=0.10  b was CANCELLED
t=0.10  c was CANCELLED
t=0.10  except* caught 1 error: a failed
t=0.10  end of TaskGroup demo

With gather, the exception reached the caller at 0.10 s. But b and c were not stopped. They kept running and printed "finished" at 0.30 s and 0.50 s, long after the caller had moved on. In a real service those two would be holding database connections and doing work whose result nobody will ever read. Those are orphan tasks.

With TaskGroup, the failure at 0.10 s made the group cancel b and c immediately (both lines show "CANCELLED" at 0.10 s). Only after both had stopped did the group raise. Nothing is left running when the async with block exits, whether it ended well or badly.

That guarantee is what "structured concurrency" means: tasks live inside a block, and the block does not end until every task inside it has ended. It works like a with statement for tasks. Fig. 19.17 draws the same timeline.

One child fails: gather versus TaskGroup (times measured) asyncio.gather: the error is raised, the siblings keep running task a task b task c fails still running ... finishes at 0.30 s, nobody asked it to still running ... finishes at 0.50 s gather raises ValueError at 0.10 s; the caller carries on while b and c are still working in the background. asyncio.TaskGroup: one failure cancels the siblings, then the group raises task a task b task c fails cancelled cancelled the group catches the first error b gets CancelledError at 0.10 s, cleans up c gets CancelledError at 0.10 s, cleans up, then ExceptionGroup is raised
Fig. 19.17 — Failure propagation. With gather the first error reaches the caller while b and c run on (they finished at 0.30 s and 0.50 s). With TaskGroup a's error cancels b and c at 0.10 s and the group raises one ExceptionGroup only after every child has stopped.

Bridge: exception groups and except*

What does a group raise when two children fail at the same time? One exception cannot describe two errors. Python 3.11 added exception groups (PEP 654): an ExceptionGroup is an exception that carries a list of other exceptions.

To handle them you use except* (read it "except star"). Each except* clause takes out of the group the exceptions that match its type, and the remaining ones carry on to the next clause. More than one clause can run for one group.

exception_groups.py · Python 3.14runs offline
import asyncio


async def bad_tax():
    raise ValueError("tax service returned 500")


async def bad_promo():
    raise KeyError("promo FIRST50 missing")


async def slow_ok():
    await asyncio.sleep(1)


async def main():
    try:
        async with asyncio.TaskGroup() as tg:
            tg.create_task(bad_tax())
            tg.create_task(bad_promo())
            tg.create_task(slow_ok())
    except* ValueError as group:
        print("ValueError branch:", [str(e) for e in group.exceptions])
    except* KeyError as group:
        print("KeyError branch:  ", [repr(e) for e in group.exceptions])


asyncio.run(main())


# what a plain "except ValueError" sees
async def plain():
    async with asyncio.TaskGroup() as tg:
        tg.create_task(bad_tax())

try:
    asyncio.run(plain())
except ValueError:
    print("plain except ValueError: caught")
except Exception as e:
    print("plain except missed it:", type(e).__name__, "-", e)
output · Python 3.14.7runs offline
ValueError branch: ['tax service returned 500']
KeyError branch:   ["KeyError('promo FIRST50 missing')"]
plain except missed it: ExceptionGroup - unhandled errors in a TaskGroup (1 sub-exception)

The first two lines show the group being split: the ValueError went to the first clause and the KeyError to the second, and both ran. The slow third task was cancelled, so the program did not wait one second for it.

The last line is the trap. A plain except ValueError does not catch a ValueError that is inside a group. What arrives is an ExceptionGroup, which is not a ValueError. So when you move from gather to TaskGroup, every except around it must become except*. Otherwise your handler silently stops matching.

Idiom: Run related tasks in a TaskGroup

The problem: you start several tasks for one request. One fails, the request is already lost, but the siblings keep running, keep their connections open, and may even write results that nobody reads.

How it works: put the tasks in async with asyncio.TaskGroup() as tg. The block is a unit of work. It ends only when all children have ended, and a failure of any child cancels the rest.

  1. Open the group: async with asyncio.TaskGroup() as tg: and start children with tg.create_task(coro()).
  2. Collect results from the tasks: keep the task objects and read task.result() after the block, when you know every one is done.
  3. Handle failures with except*: wrap the whole async with in try and use except* for each error type you can handle. Let the rest propagate.
  4. Add a deadline from outside: wrap the group in async with asyncio.timeout(2.0):. On timeout every child is cancelled.

Without the idiom (the first five lines of the output above): gather returns the error early, and the siblings finish later, unsupervised.

gather: the siblings outlive the errorruns offline
--- gather ---
t=0.10  gather raised: a failed  (siblings still running)
t=0.30  b finished
t=0.50  c finished
t=0.70  end of gather demo

With the idiom (the next six lines): the siblings are cancelled and the error arrives as a group, after everything has stopped.

TaskGroup: nothing outlives the blockruns offline
--- TaskGroup ---
t=0.10  b was CANCELLED
t=0.10  c was CANCELLED
t=0.10  except* caught 1 error: a failed
t=0.10  end of TaskGroup demo

Bridge: cancellation and timeouts

You saw that a group stops its children by cancelling them. To cancel a task, asyncio throws a CancelledError into it, at the point where it is currently waiting at an await. The task is expected to clean up and let the error continue upward, so that the loop learns the task is really finished.

Two details explain most cancellation bugs. First, CancelledError is a subclass of BaseException, not of Exception, so an ordinary except Exception does not catch it. Second, a task that catches it and does not re-raise tells the loop "I am still alive", and the loop believes it.

The setup: two background workers. One swallows the cancel, one uses finally and lets it through. After cancel() we check task.done(). Then a timeout and a shield.

cancel_and_timeout.py · Python 3.14runs offline
import asyncio


shutting_down = False


async def swallow():                       # ❌ TRAP
    while not shutting_down:
        try:
            await asyncio.sleep(0.05)
        except asyncio.CancelledError:
            print("  swallow(): got cancelled, ignoring it")


async def polite():                        # ✅
    try:
        while True:
            await asyncio.sleep(0.05)
    finally:
        print("  polite(): cleaning up, then letting cancel through")


async def slow_rule():
    await asyncio.sleep(10)


async def main():
    for fn in (swallow, polite):
        t = asyncio.create_task(fn())
        await asyncio.sleep(0.12)
        t.cancel()
        await asyncio.sleep(0.2)
        print(f"{fn.__name__}: task.done() = {t.done()}")
        if not t.done():
            print("  ... cancel() did not stop it")
    try:
        async with asyncio.timeout(0.2):
            await slow_rule()
    except TimeoutError:
        print("asyncio.timeout(0.2): TimeoutError raised, slow_rule cancelled")
    print("shield:")
    inner = asyncio.create_task(asyncio.sleep(0.3, result="payment saved"))
    try:
        async with asyncio.timeout(0.1):
            await asyncio.shield(inner)
    except TimeoutError:
        print("  caller timed out after 0.1 s ...")
    print(f"  ... but the shielded task finished anyway: {await inner}")


async def run():
    global shutting_down
    await main()
    shutting_down = True    # only so this demo can exit


asyncio.run(run())
output · Python 3.14.7runs offline
  swallow(): got cancelled, ignoring it
swallow: task.done() = False
  ... cancel() did not stop it
  polite(): cleaning up, then letting cancel through
polite: task.done() = True
asyncio.timeout(0.2): TimeoutError raised, slow_rule cancelled
shield:
  caller timed out after 0.1 s ...
  ... but the shielded task finished anyway: payment saved
  swallow(): got cancelled, ignoring it

Read the output in four parts.

The very last line of the output is the program shutting down. asyncio.run cancels every task still alive when main returns, and the swallowing task printed once more. I set a flag only so the demo could exit. A real swallower would have kept asyncio.run waiting forever.

The rule is short. Catch CancelledError only to clean up, and always raise again. Prefer try/finally or async with, which clean up and let the error through without any except at all.

Idiom: Keep a reference to every fire-and-forget task

The problem: you write asyncio.create_task(audit(order)) to log an audit record in the background and do not store the result. Sometimes the audit simply never happens, and no error is shown.

How it works: the event loop keeps only a weak reference to the tasks it is running. A weak reference does not keep an object alive. If nothing else points at a task, and the task is waiting on something that nothing else points at either, the garbage collector may destroy it half-way. The documentation says plainly: save a reference to the result of create_task.

  1. Add the task to a set that lives as long as the application: background.add(task).
  2. Remove it when it ends: task.add_done_callback(background.discard). The set cannot grow forever.
  3. Better, give the task an owner: start it in a TaskGroup that lives for the whole application, or in the request's own group if the work should end with the request.

The failure depends on what the task is waiting for. A task waiting on a timer is also referenced by the timer inside the loop, so it usually survives. A task waiting on a future that no one else holds is referenced by nothing. We test both.

keep_task_refs.py · Python 3.14runs offline
import asyncio
import gc

done = []
background: set[asyncio.Task] = set()


async def audit_sleep(n):                   # waits on a timer
    await asyncio.sleep(0.05)
    done.append(n)


async def audit_wait(n, fut):               # waits on a future nobody else holds
    await fut
    done.append(n)


async def main():
    loop = asyncio.get_running_loop()
    # ❌ TRAP: no reference kept
    asyncio.create_task(audit_sleep("sleep, no ref"))
    asyncio.create_task(audit_wait("future, no ref", loop.create_future()))
    # ✅ keep a strong reference until the task is done
    t = asyncio.create_task(audit_sleep("sleep, kept"))
    background.add(t)
    t.add_done_callback(background.discard)
    gc.collect()
    await asyncio.sleep(0.2)
    gc.collect()
    print("finished:", done)
    print("still tracked:", len(background))


asyncio.run(main())
output · Python 3.14.7runs offline
Task was destroyed but it is pending!
task: <Task pending name='Task-3' coro=<audit_wait() running at /home/iam100god/Desktop/AI_COURSE/code/e19-python-deep-dive/C/keep_task_refs.py:14> wait_for=<Future pending cb=[Task.task_wakeup()]>>
finished: ['sleep, no ref', 'sleep, kept']
still tracked: 0

The two outcomes are honest, and they teach different things. The task that waited on a timer finished even without a reference ("sleep, no ref" is in the list), so the bug did not reproduce there. That is why this bug is so nasty: it passes in your tests and in staging.

The task that waited on a future nobody else held was destroyed by the garbage collector. Python printed "Task was destroyed but it is pending!", and "future, no ref" is missing from the finished list. The task with a saved reference completed, and the set was empty afterwards, so nothing leaked.

Whether a particular task is collected depends on timing and on what it awaits. You cannot test for it reliably. So you do not try; you follow the documented pattern every time.

Idiom: Bound concurrency with a Semaphore

The problem: pricer refreshes 100 menu prices from a partner API. The easy code starts all 100 calls at once with gather. The partner allows 10 at a time, answers the 11th onwards with HTTP 429 "too many requests", and your connection pool of 10 starts to time out.

How it works: an asyncio.Semaphore(10) is a counter that starts at 10. async with sem: takes one from the counter on entry and gives it back on exit. When the counter is zero, the next task waits at the async with line, without blocking the loop, until somebody finishes.

  1. Create the semaphore once and share it with every task: sem = asyncio.Semaphore(10).
  2. Hold it only around the outbound call, not around the whole task: async with sem: await client.get(url).
  3. Start all tasks anyway: a task that is waiting on the semaphore costs a few hundred bytes. If you have a million items, feed them through a bounded queue instead of creating a million tasks.
semaphore_bound.py · Python 3.14runs offline
import asyncio
import time

in_flight = 0
peak = 0


async def call(sem, i):
    global in_flight, peak
    async with sem:
        in_flight += 1
        peak = max(peak, in_flight)
        await asyncio.sleep(0.1)
        in_flight -= 1


async def main(limit):
    global peak
    peak = 0
    sem = asyncio.Semaphore(limit)
    t0 = time.perf_counter()
    await asyncio.gather(*(call(sem, i) for i in range(100)))
    print(f"limit={limit:<4} total={time.perf_counter() - t0:5.2f} s  max in flight={peak}")


asyncio.run(main(10))
asyncio.run(main(100))
output · Python 3.14.7runs offline
# measured on the course machine; the 1.01 s will differ a little on yours
limit=10   total= 1.01 s  max in flight=10
limit=100  total= 0.10 s  max in flight=100

The arithmetic is the lesson. 100 calls of 0.1 s with at most 10 at a time is 100 / 10 = 10 rounds of 0.1 s, about 1.0 s. We measured 1.01 s, and the program counted that the number in flight never went above 10. With the limit set to 100 (the second line, as a control) the same job takes 0.10 s and 100 calls are in flight together. The semaphore is the dial between "fast" and "polite".

Idiom: Carry request context with contextvars

The problem: you want every log line to carry the request id, without passing request_id through twenty function signatures. The classic tool is threading.local(), a variable with a separate value for each thread. It works in a threaded server. Move the same code to asyncio and the ids get mixed up between customers.

How it works: all tasks in an asyncio program run on one thread, so a threading.local is one single shared slot for all of them. A contextvars.ContextVar instead lives in a context, a small dictionary-like object. Every task gets a copy of the creating context when it starts, so a value you set inside a task is visible only to that task and the code it awaits.

  1. Declare once at module level: request_id = ContextVar("request_id", default="-").
  2. Set at the edge: in the middleware that handles one request, call request_id.set(rid). Keep the returned token if you want to reset the value afterwards.
  3. Read anywhere below: logging filters and deep functions call request_id.get().
  4. Threads started with to_thread inherit it: to_thread copies the current context into the worker thread, which a plain threading.Thread does not.

The setup: three requests handled at once. Each handler stores its id in both a ContextVar and a threading.local, waits a little, then calls a deep function that reads both.

contextvars_vs_local.py · Python 3.14runs offline
import asyncio
import contextvars
import threading

request_id = contextvars.ContextVar("request_id", default="-")
local = threading.local()


async def deep_call(tag):
    await asyncio.sleep(0.01)        # other requests run here
    return f"{tag:<14} contextvar={request_id.get()}  threading.local={getattr(local, 'rid', '-')}"


async def handle(rid):
    request_id.set(rid)
    local.rid = rid
    await asyncio.sleep(0.01 * (rid == "req-B"))   # interleave differently
    print(await deep_call(f"handler {rid}"))


async def main():
    await asyncio.gather(handle("req-A"), handle("req-B"), handle("req-C"))


asyncio.run(main())

What you see:

output · Python 3.14.7runs offline
handler req-A  contextvar=req-A  threading.local=req-C
handler req-C  contextvar=req-C  threading.local=req-C
handler req-B  contextvar=req-B  threading.local=req-C

Look at the first column after the handler name. The ContextVar always returns the id of the request that is running, even though the three handlers were interleaved. The threading.local column says req-C for every handler. All three tasks wrote into the same slot on the same thread, and the last writer won. If this were your log filter, customer A's log lines would carry customer C's request id, and an investigation would be built on the wrong facts.

Bridge: threads, the primitives you actually use

Threads are older than asyncio and still the right tool when you must use a blocking library. In practice, five tools cover almost every case, and the rest of threading is rarely needed.

The thread tools worth knowing, and what each one is for
ToolWhat it isUse it when
ThreadPoolExecutorA fixed set of worker threads that take jobs and return futures.You have N independent blocking calls. It is the default choice.
queue.QueueA thread-safe line of work. put and get do the locking for you.Producer and consumer threads, with a sentinel value to say "stop".
threading.LockOne thread at a time inside a with lock: block.A shared value is read and then changed (counter += 1, a dictionary entry check-then-set).
threading.EventA flag that one thread sets and others can wait on or poll.Clean shutdown: "stop working now".
threading.localA per-thread variable.Per-thread state in a threaded server. Not for asyncio (see the idiom above).

The queue is the one that deserves a small example, because it replaces most explicit locking. Workers never touch a shared list. They only get from one queue and put on another, and the queue handles the safety. The program also shows a lock around a shared counter, which Section 05 explains in detail.

queue_workers.py · Python 3.14runs offline
import queue
import threading

jobs: queue.Queue = queue.Queue()
results: queue.Queue = queue.Queue()
STOP = object()                              # sentinel: "no more work"


def worker():
    while True:
        job = jobs.get()                     # blocks until something arrives
        if job is STOP:
            return
        results.put((job, job * 100))        # pretend: price order `job`


threads = [threading.Thread(target=worker) for _ in range(3)]
for t in threads:
    t.start()
for order_id in range(1, 7):
    jobs.put(order_id)
for _ in threads:
    jobs.put(STOP)                           # one stop sign per worker
for t in threads:
    t.join()

print(sorted(results.get() for _ in range(results.qsize())))

counter = 0
lock = threading.Lock()


def bump():
    global counter
    for _ in range(100_000):
        with lock:                           # ✅ the invariant is protected by YOU
            counter += 1


ts = [threading.Thread(target=bump) for _ in range(4)]
for t in ts:
    t.start()
for t in ts:
    t.join()
print("counter with a lock:", counter)
output · Python 3.14.7runs offline
[(1, 100), (2, 200), (3, 300), (4, 400), (5, 500), (6, 600)]
counter with a lock: 400000

Three workers priced six orders. I sorted the result before printing, because the order in which threads finish is not fixed. The counter is exactly 400,000 because every += 1 happened inside with lock. Without the lock, the number depends on the interpreter, and Section 05 shows when it goes wrong.

Bridge: why Ctrl+C does not stop a threaded program

A common production surprise: you press Ctrl+C, or your platform sends SIGINT or SIGTERM on a deploy, and the program does not stop. The reason is how Python ends a process. When the main thread finishes, the interpreter waits (it joins) for every non-daemon thread before it exits. A daemon thread is one marked daemon=True, which the interpreter does not wait for; it is killed abruptly when the process exits.

Only the main thread receives the signal. A worker thread that loops "forever" never sees it. So the interpreter waits for a loop that will not end.

The setup: a worker that needs 1.0 s of work, and a "Ctrl+C" (SIGINT) sent to the process after 0.3 s. First with a normal thread, then with daemon=True.

ctrl_c_threads.py · Python 3.14runs offline
import os
import signal
import sys
import threading
import time

T0 = time.perf_counter()
daemon = sys.argv[1] == "daemon"


def now():
    return f"{time.perf_counter() - T0:4.2f} s"


def worker():
    for i in range(10):                 # ten steps of 0.1 s
        time.sleep(0.1)
    print(f"worker finished all 10 steps at {now()}")


threading.Thread(target=worker, daemon=daemon).start()
threading.Timer(0.3, os.kill, (os.getpid(), signal.SIGINT)).start()   # "Ctrl+C" at 0.3 s
try:
    time.sleep(5)
except KeyboardInterrupt:
    print(f"main: KeyboardInterrupt at {now()}, main thread ends")
output · Python 3.14.7runs offline
--- nondaemon
main: KeyboardInterrupt at 0.30 s, main thread ends
worker finished all 10 steps at 1.00 s
--- daemon
main: KeyboardInterrupt at 0.30 s, main thread ends

With the normal thread, the main thread ended at 0.30 s, but the process lived until 1.00 s, because Python waited for the worker to finish all ten steps. Here the wait is one second. With a worker loop of while True, the wait would be forever.

With the daemon thread the process ended right away, and the worker's "finished" line never appears: it was cut off half-way. That is also dangerous. A daemon thread can be stopped in the middle of writing a file or a database row.

The clean answer is neither. Use a threading.Event, as in the earlier shutdown_event.py idea: workers check while not stop.is_set() and wait on a queue with a timeout, the signal handler calls stop.set(), and the main thread joins the workers.

shutdown_event.py · Python 3.14runs offline
import threading
import time

stop = threading.Event()


def worker(n):
    while not stop.is_set():
        time.sleep(0.05)               # pretend: poll a queue
    print(f"worker {n} saw the stop flag and exited")


threads = [threading.Thread(target=worker, args=(i,)) for i in range(2)]
for t in threads:
    t.start()
time.sleep(0.2)
print("main: setting the stop event (what a SIGINT handler would do)")
stop.set()
for t in threads:
    t.join()
print("main: all workers joined, process can exit")
output · Python 3.14.7runs offline
main: setting the stop event (what a SIGINT handler would do)
worker 1 saw the stop flag and exited
worker 0 saw the stop flag and exited
main: all workers joined, process can exit

Both workers saw the flag, finished the step they were on, and exited, so the process ended without losing work. In a real service the signal handler (or loop.add_signal_handler in asyncio) calls stop.set(), and the workers use queue.get(timeout=0.5) so that they notice the flag even when no work arrives.

Java · ExecutorService

Submit callables, get futures. CompletableFuture.allOf waits for all of them.

Fanout.javaruns offline
var pool = Executors.newFixedThreadPool(8);
var fs = orders.stream()
    .map(o -> CompletableFuture
        .supplyAsync(() -> price(o), pool))
    .toList();
CompletableFuture
    .allOf(fs.toArray(new CompletableFuture[0]))
    .join();

Python · concurrent.futures / asyncio

The same shape for threads, and a coroutine version.

fanout.py · Python 3.14runs offline
with ThreadPoolExecutor(8) as pool:
    results = list(pool.map(price, orders))

# or, in async code:
results = await asyncio.gather(
    *(price(o) for o in orders)
)

The shift: in Java you build a list of futures and join them yourself. In Python pool.map does the submit-and-collect in one call, and leaving the with block waits for the pool, so shutting down the pool is part of the syntax.

Bridge: processes, and how a new worker is started

Threads share memory, and that is exactly what the GIL makes awkward for CPU-bound Python. A process is the other answer: a separate copy of the interpreter with its own memory and its own GIL. Four processes can use four cores at once, on any Python version.

The price is that processes cannot see each other's objects. Everything that crosses between them, arguments and results, is turned into bytes with pickle, sent through a pipe, and rebuilt on the other side. That copy is the cost to watch.

Before the cost, one more thing: how a worker process comes to exist. Python offers three start methods, and the default changed.

The three multiprocessing start methods
Start methodHow the worker is createdGoodCatch
forkThe operating system copies the running parent process, memory and all.Fast. The worker already has your imported modules and data.It copies only the calling thread. If another thread held a lock at that moment, the child inherits a lock that nobody will ever release.
spawnA fresh interpreter starts and imports your main module again.Clean and predictable. The only choice on Windows, and the default on macOS.Slow start. Your main module is run again, so it needs if __name__ == "__main__" (see the idiom in Section 05).
forkserverOne small clean server process is started early; it forks workers on request.Workers start from a clean state without re-running your whole program, and without inheriting threads.Needs the main-module guard too, and arguments must be picklable.

Which one do you get if you ask for nothing? Do not trust memory; ask the interpreters.

start_methods.py · run on 3.12 and then on 3.14runs offline
import multiprocessing
import sys

print(sys.version.split()[0], "default start method:", multiprocessing.get_start_method())
print("available:", multiprocessing.get_all_start_methods())
output · 3.12.3 first, then 3.14.7runs offline
3.12.3 default start method: fork
available: ['fork', 'spawn', 'forkserver']
3.14.7 default start method: forkserver
available: ['forkserver', 'fork', 'spawn']

On Python 3.12 Linux the default is fork. On Python 3.14 it is forkserver. The same is true for the free-threaded 3.14t build. This is a real behaviour change between versions. Code that worked by accident under fork (a module-level global shared with the child, a lambda passed as a task, a missing main guard) can break when you upgrade. The standard fix is to be explicit: call multiprocessing.set_start_method("spawn") yourself, or pass a context, multiprocessing.get_context("spawn").

Why a fork can deadlock. Imagine pricer's parent process has a logging thread. At the instant of the fork, that thread is in the middle of writing a log line, holding the logging lock. The child gets a copy of memory, including the lock in the "held" state, but not the thread that would release it.

The first time the child logs, it waits for a lock that nobody owns. It hangs at start-up, usually in production only, because it depends on the timing of the other thread. I am not reproducing this one: a deadlock that depends on timing makes a poor demo. The defence is the same as above: avoid fork in programs that use threads, and prefer forkserver or spawn.

Bridge: the pickling bill

Now the cost. Consider a task so small that doing it takes a fraction of a microsecond: apply 21 percent VAT to a price in cents. We run it for 20,000 prices three ways: in a plain loop, in a pool with one task per submission, and in a pool with 1,000 prices per submission (chunksize). Then we compare a task that is really heavy.

pool_chunks.py · Python 3.14runs offline
import time
from concurrent.futures import ProcessPoolExecutor


def vat(cents):                      # tiny task: ~100 ns of real work
    return cents * 21 // 100


def vat_chunk(chunk):                # one big task: the loop runs inside the worker
    return [c * 21 // 100 for c in chunk]


def heavy(n):                        # a task that is really CPU-heavy
    total = 0
    for i in range(n):
        total += i * i % 7
    return total


if __name__ == "__main__":
    data = list(range(20_000))

    t = time.perf_counter()
    serial = [vat(c) for c in data]
    print(f"serial, tiny tasks            {time.perf_counter() - t:6.3f} s")

    with ProcessPoolExecutor(4) as pool:
        t = time.perf_counter()
        out = list(pool.map(vat, data))                       # chunksize=1
        print(f"pool, 20,000 tasks, chunk=1   {time.perf_counter() - t:6.3f} s")
        t = time.perf_counter()
        out = list(pool.map(vat, data, chunksize=1_000))
        print(f"pool, chunksize=1,000          {time.perf_counter() - t:6.3f} s")

    t = time.perf_counter()
    heavy_serial = [heavy(2_000_000) for _ in range(8)]
    print(f"serial, 8 heavy tasks         {time.perf_counter() - t:6.3f} s")
    with ProcessPoolExecutor(4) as pool:
        t = time.perf_counter()
        out = list(pool.map(heavy, [2_000_000] * 8))
        print(f"pool(4), 8 heavy tasks        {time.perf_counter() - t:6.3f} s")
output · Python 3.14.7runs offline
# measured on the course machine (12 cores); your numbers will differ
serial, tiny tasks             0.003 s
pool, 20,000 tasks, chunk=1    3.111 s
pool, chunksize=1,000           0.020 s
serial, 8 heavy tasks          1.008 s
pool(4), 8 heavy tasks         0.282 s

Read it line by line.

So the rule has two halves. Processes help when each unit of work is large (milliseconds or more) and its input and output are small. They hurt when the tasks are tiny, or when each task has to carry a big object.

Idiom: Process pool with big units of work

The problem: you "parallelised" a loop with ProcessPoolExecutor and it became slower than the plain loop, or it used four times the memory for no gain. The tasks are too small, or each task copies a large object into the worker.

How it works: make each task big enough to cost far more than its own pickling, and keep what travels across the pipe small.

  1. Measure the unit first: time one task in the plain loop. If it is under about a millisecond, batch many items into one task.
  2. Batch with chunksize or explicit chunks: pool.map(fn, items, chunksize=1000), or send a list of 1,000 items as one argument and return one list.
  3. Send identifiers, not objects: pass a file path, an id range or a row range; let the worker load its own data. Never pass a 200 MB object to every task.
  4. Create the pool once and reuse it (with ProcessPoolExecutor(n) as pool: at start-up). Starting workers costs tens of milliseconds each.
  5. Guard the main module with if __name__ == "__main__":, as the idiom in Section 05 shows. The default start method on 3.14 needs it.

Without the idiom (copied from the output above):

one tiny task per submissionruns offline
pool, 20,000 tasks, chunk=1    3.111 s

With the idiom (batched, then genuinely heavy tasks):

big units of workruns offline
pool, chunksize=1,000           0.020 s
serial, 8 heavy tasks          1.008 s
pool(4), 8 heavy tasks         0.282 s

Bridge: subinterpreters, processes with less weight

Python 3.14 added a fourth option to the standard library (PEP 734): concurrent.interpreters. A subinterpreter is a second, isolated Python interpreter that lives inside the same process. It has its own modules, its own global names and its own objects. Since Python 3.12 (PEP 684) each one can also have its own GIL, so subinterpreters on different threads can run Python at the same time.

Think of it as a process without the process: no separate operating-system memory, so it starts faster and uses less memory, but the same strong isolation of objects. Here is the real API on 3.14.

interpreters_demo.py · Python 3.14 (run with python -u)runs offline
from concurrent import interpreters
from concurrent.futures import InterpreterPoolExecutor
import threading


def square(n):
    return n * n


counter = 5                            # a global in the MAIN interpreter

# 1. one sub-interpreter, run a string of code in it
interp = interpreters.create()
interp.exec("secret = 42; print('inside the sub-interpreter, secret =', secret)")
try:
    interp.exec("print(counter)")      # main's globals are NOT visible
except interpreters.ExecutionFailed as e:
    print("main has counter = 5, but the sub-interpreter raised:", e.excinfo.type.__name__)

# 2. call a function in it, get the result back

print("interp.call(square, 12) =", interp.call(square, 12))
interp.close()

# 3. the pool, like ThreadPoolExecutor but with isolated interpreters
if __name__ == "__main__":
    with InterpreterPoolExecutor(max_workers=3) as pool:
        print("pool.map:", list(pool.map(square, range(6))))
    print("threads alive after:", threading.active_count())
output · Python 3.14.7runs offline
inside the sub-interpreter, secret = 42
main has counter = 5, but the sub-interpreter raised: NameError
interp.call(square, 12) = 144
pool.map: [0, 1, 4, 9, 16, 25]
threads alive after: 1

Four things to read off the output.

  1. Code runs inside it: interp.exec(source) ran a string of code in the second interpreter and printed from it.
  2. Isolation is real: the main program has counter = 5, yet the subinterpreter raised NameError on counter. Nothing is shared by default.
  3. Calling functions works, with copying: interp.call(square, 12) sent the function and the argument over and got 144 back. Arguments and results must be of simple, shareable kinds.
  4. A pool exists: InterpreterPoolExecutor has the same shape as ThreadPoolExecutor and ProcessPoolExecutor, so switching models is a one-word change.

Does it speed up CPU-bound work? We run the same eight heavy tasks through four kinds of pool on 3.14, and then on the free-threaded 3.14t.

interpreter_cpu.py · Python 3.14 and 3.14truns offline
import time
from concurrent.futures import InterpreterPoolExecutor, ProcessPoolExecutor, ThreadPoolExecutor


def heavy(n):
    total = 0
    for i in range(n):
        total += i * i % 7
    return total


def run(name, pool_cls):
    with pool_cls(4) as pool:
        list(pool.map(heavy, [10_000]))          # warm up the workers
        t = time.perf_counter()
        list(pool.map(heavy, [2_000_000] * 8))
        print(f"{name:<24}{time.perf_counter() - t:6.3f} s")


if __name__ == "__main__":
    t = time.perf_counter()
    [heavy(2_000_000) for _ in range(8)]
    print(f"{'serial':<24}{time.perf_counter() - t:6.3f} s")
    run("ThreadPoolExecutor(4)", ThreadPoolExecutor)
    run("InterpreterPool(4)", InterpreterPoolExecutor)
    run("ProcessPool(4)", ProcessPoolExecutor)
output · Python 3.14.7 (standard build)runs offline
# measured on the course machine; single runs, so read the ratios, not the digits
serial                   1.025 s
ThreadPoolExecutor(4)    2.532 s
InterpreterPool(4)       0.317 s
ProcessPool(4)           0.307 s
output · Python 3.14.7t (free-threaded build)runs offline
# same script, same machine
serial                   1.137 s
ThreadPoolExecutor(4)    0.295 s
InterpreterPool(4)       0.375 s
ProcessPool(4)           0.318 s
Eight CPU-bound tasks on four workers (measured, seconds)
ModelPython 3.14 (GIL)Python 3.14t (no GIL)Reading
Serial loop1.0251.137The baseline.
4 threads2.5320.295With the GIL, slower than serial. Without it, 3.9 times faster than serial on this run.
4 subinterpreters0.3170.375About 3.2 times faster than serial on the standard build, with no process start-up.
4 processes0.3070.318About 3.3 times faster on the standard build. The safe baseline.

Three honest observations. First, threads with the GIL got slower than the plain loop (2.53 s against 1.03 s). The four threads fight over one lock, and each hand-over costs time. Second, subinterpreters and processes landed within a few percent of each other.

The saving of subinterpreters is memory and start-up time, not raw speed here. Third, on the free-threaded build the plain loop is a little slower (1.14 s against 1.03 s), which is the single-thread cost that Section 05 measures on its own benchmark (about 23 percent there), but threads then scale almost like processes.

When is a subinterpreter worth it? When you want parallel pure-Python work in one process, tasks are mostly isolated, and your extension modules support it. When it is not: when libraries have not been made safe for it yet, when tasks must share objects, or when your team does not want to be early on a young API. Check the Python 3.14 "What's New" page for the current list of supported extensions before you adopt it.

Choosing between the CPU-bound options (the stack rule: alternatives, why this one, when to switch)
OptionPick it whenCost or catch
Native code (numpy, Cython, Rust)The hot loop is numbers or bytes. Usually the biggest win by far.A build step or a new dependency, and a rewrite of the hot part.
ProcessPoolExecutorPure-Python CPU work, any Python version, tasks of milliseconds or more.Pickling, start-up, memory per process.
InterpreterPoolExecutor (3.14)You want process-like isolation with less memory and start-up cost.Young API, extension-module support varies, data must be copyable.
Threads on python3.14tMany tasks share a large in-memory structure and you can use the free-threaded build.Separate build, single-thread slowdown, every shared value needs a lock.
More machinesOne machine is not enough, or tasks must survive restarts.A queue, a broker and operations work (see Chapter E17).

That closes the concurrency models. The one-sentence rule: waiting is a job for asyncio or threads, computing is a job for native code first and then processes, interpreters or free-threading, and you choose by measuring a small version of your real task.

07 · ToolingTypes, Packaging, Testing and Performance in a Real Codebase

Python's language is the small part of a production codebase. The rest is type checking, a locked set of dependencies, tests that actually test, and a habit of measuring before optimising. This section shows each one working on pricer, ends with a small typed and tested package you can run, and says where each tool stops helping.

Two incidents hit pricer in the same week. On Tuesday the service crashes with AttributeError: 'NoneType' object has no attribute 'amount'. The line is rule.amount, inside a function that calls find_rule(code). When a customer types a code that does not exist, find_rule returns None, and the next line treats it as a rule.

On Friday a deploy fails. Nobody changed a line of pricer. A library that pricer depends on, through another library that it depends on, published a new minor version that morning. The Friday build installed it, and it behaved differently. The Tuesday build, a few days earlier, had not.

These are two different failures, but one cause: the system accepted something it should have refused. Tuesday's crash is what a type checker is for. Friday's is what a lockfile is for. We start with Tuesday.

Bridge: type hints are notes, not rules

The first fact to be sure of: Python does not enforce type hints at runtime. The hints are stored on the function and then ignored. A separate program, a type checker, reads them and complains before you run the code. If you do not run one, the hints are documentation that can lie.

hints_not_enforced.py · Python 3.12runs offline
def total_cents(price_cents: int, qty: int) -> int:
    return price_cents * qty


print(total_cents("ab", 3))          # wrong type: Python does not care
print(total_cents(5, "3"))         # a str repeated is "valid" too
print(total_cents.__annotations__)
output · Python 3.12.3runs offline
ababab
33333
{'price_cents': <class 'int'>, 'qty': <class 'int'>, 'return': <class 'int'>}

The function says int twice. It happily multiplied a string by 3 ("abab" repeated, giving ababab) and an integer by a string ("3" repeated 5 times). No error, no warning. Python only stores the hints in __annotations__, as the last line shows.

Now Tuesday's bug. The function find_rule is honest in its signature: it returns Rule | None. The caller ignores that.

find_rule_bug.py · Python 3.12runs offline
from dataclasses import dataclass


@dataclass
class Rule:
    name: str
    amount: int


RULES = {"FIRST50": Rule("FIRST50", 500)}


def find_rule(code: str) -> Rule | None:
    return RULES.get(code)


def discount(code: str) -> int:
    rule = find_rule(code)
    return rule.amount                       # ❌ TRAP: rule may be None


def discount_fixed(code: str) -> int:
    rule = find_rule(code)
    if rule is None:                         # ✅ narrowing
        return 0
    return rule.amount


print(discount("FIRST50"))
print(discount_fixed("TYPO"))
print(discount("TYPO"))

Make the invisible visible: the same file, first run, then checked by mypy.

python find_rule_bug.py (last lines)runs offline
# the first two prints (500 and 0) are cut; the traceback ends in the production error
500
0
Traceback (most recent call last):
  File "/home/iam100god/Desktop/AI_COURSE/code/e19-python-deep-dive/C/find_rule_bug.py", line 31, in <module>
    print(discount("TYPO"))
          ^^^^^^^^^^^^^^^^
  File "/home/iam100god/Desktop/AI_COURSE/code/e19-python-deep-dive/C/find_rule_bug.py", line 19, in discount
    return rule.amount                       # ❌ TRAP: rule may be None
           ^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'amount'
mypy find_rule_bug.pyruns offline
find_rule_bug.py:19: error: Item "None" of "Rule | None" has no attribute "amount"  [union-attr]
Found 1 error in 1 file (checked 1 source file)

Python ran fine for the code that exists and crashed on the one that does not, with exactly the production message. mypy reads the same file without running it and reports line 19: Item "None" of "Rule | None" has no attribute "amount". The checker knows the function can return None, so it refuses the attribute access.

The fix on the checker's terms is the if rule is None branch in discount_fixed. After the if, mypy narrows the type: it knows that in the rest of the function rule is a Rule, so rule.amount is fine. This check costs nothing at runtime.

Two terms you will be asked about. Gradual typing means you can add hints to a few functions and leave the others untyped. The checker checks only what is annotated, so you adopt types one module at a time. The special type Any is the escape hatch that makes this possible, and it is also the danger.

Any means "turn off checking for this value". object means "this is some object, and I will only use what every object has". They look alike and behave oppositely.

any_vs_object.py · checked with mypyruns offline
from typing import Any


def from_json_any(payload: Any) -> int:
    return payload["qty"] * 2          # checker: silent, anything goes


def from_json_object(payload: object) -> int:
    return payload["qty"] * 2          # checker: refuses, object has no __getitem__


def spread(payload: Any) -> None:
    qty = payload["qty"]               # qty is Any too ...
    total = qty.nonexistent_method()   # ... so this typo is invisible
    reveal_type(qty)
    reveal_type(total)
mypy any_vs_object.pyruns offline
any_vs_object.py:9: error: Value of type "object" is not indexable  [index]
any_vs_object.py:15: note: Revealed type is "Any"
any_vs_object.py:16: note: Revealed type is "Any"
Found 1 error in 1 file (checked 1 source file)

The Any function is accepted without any complaint, even though it indexes a value that may not be indexable. The object function is refused, because an object has no [], which forces you to check the type first.

And the last function shows how Any spreads: qty read from an Any is itself Any, and so is anything computed from it, so a typo like nonexistent_method is invisible. One Any at a boundary (such as a parsed JSON payload) quietly turns off checking for everything downstream. Use object, a TypedDict or a model at the edges instead.

Bridge: generics with the 3.12 syntax

A generic function or class works for many types and still keeps track of which one. Before Python 3.12 you needed a TypeVar declared on a separate line. Since 3.12 (PEP 695) the type parameter goes in square brackets, right after the name, much like Java's <T>.

generics_695.py · Python 3.14runs offline
from typing import reveal_type

from dataclasses import dataclass


def first[T](xs: list[T]) -> T:
    return xs[0]


class Box[T]:
    def __init__(self, item: T) -> None:
        self.item = item

    def get(self) -> T:
        return self.item


type Pair[T] = tuple[T, T]


def swap[T](p: Pair[T]) -> Pair[T]:
    return (p[1], p[0])


reveal_type(first([1, 2, 3]))
reveal_type(Box("pizza").get())
reveal_type(swap((1.5, 2.5)))
x: int = first(["a", "b"])
print(first([1, 2, 3]), Box("pizza").get(), swap((1, 2)), Pair.__value__)

Make the invisible visible: what the program prints, and what mypy knows that the program does not.

python generics_695.pyruns offline
Runtime type is 'int'
Runtime type is 'str'
Runtime type is 'tuple'
1 pizza (2, 1) tuple[T, T]
mypy --python-version 3.14 generics_695.pyruns offline
generics_695.py:25: note: Revealed type is "int"
generics_695.py:26: note: Revealed type is "str"
generics_695.py:27: note: Revealed type is "tuple[float, float]"
generics_695.py:28: error: Incompatible types in assignment (expression has type "str", variable has type "int")  [assignment]
Found 1 error in 1 file (checked 1 source file)

At runtime, the line x: int = first(["a", "b"]) assigned a str to an int-annotated name and nothing happened, which is the point of the last section. mypy worked out that first([1, 2, 3]) is an int, Box("pizza").get() is a str, and swap((1.5, 2.5)) is a tuple[float, float]. It then flagged line 26, where the str result was assigned to an int variable.

The type Pair[T] = tuple[T, T] line makes a type alias. It is lazily evaluated, and you can still inspect its value at run time: Pair.__value__ printed tuple[T, T] in the last output.

Three more tools complete the everyday set. Literal restricts a value to specific constants. @overload declares that a function returns different types for different arguments. Self means "the type of the object you called this on", so chained methods on subclasses keep the subclass.

literal_overload_self.py · checked with mypyruns offline
from typing import Literal, Self, overload, reveal_type


class Basket:
    def __init__(self) -> None:
        self.items: list[str] = []

    def add(self, sku: str) -> Self:               # Self: returns the same type, subclass-safe
        self.items.append(sku)
        return self


@overload
def fetch(kind: Literal["price"]) -> int: ...
@overload
def fetch(kind: Literal["name"]) -> str: ...
def fetch(kind: str) -> int | str:
    return 250 if kind == "price" else "pizza"


Channel = Literal["app", "web"]


def route(channel: Channel) -> str:
    return channel.upper()


reveal_type(Basket().add("pizza").add("cola"))
reveal_type(fetch("price"))
reveal_type(fetch("name"))
route("phone")                                    # mypy: not one of the allowed literals
mypy literal_overload_self.pyruns offline
literal_overload_self.py:28: note: Revealed type is "literal_overload_self.Basket"
literal_overload_self.py:29: note: Revealed type is "int"
literal_overload_self.py:30: note: Revealed type is "str"
literal_overload_self.py:31: error: Argument 1 to "route" has incompatible type "Literal['phone']"; expected "Literal['app', 'web']"  [arg-type]
Found 1 error in 1 file (checked 1 source file)

The chained Basket().add(...).add(...) is a Basket. The overload gives int for "price" and str for "name" from one function. And route("phone") is rejected because the only allowed values are "app" and "web". That last check is a small version of the bug class "typo in a status string", caught before anyone runs the code.

Idiom: Describe behaviour with a Protocol

The problem: pricer has many kinds of price rule (percent off, flat off, free delivery). The code that applies them should not care which kind it has, but you want the checker to catch a rule whose method has the wrong shape. A common answer is an abstract base class that every rule must inherit. That forces every rule, including ones in other libraries, to import and subclass your class.

How it works: a typing.Protocol lists the methods and attributes a type must have. Any class that has them counts, with no inheritance. This is structural typing: compatibility is decided by shape. It is the typed version of duck typing ("if it walks like a duck").

  1. Declare the shape: class PriceRule(Protocol): with the method signatures and ... bodies.
  2. Use it in signatures: def run(rule: PriceRule, ...). Callers pass anything that fits.
  3. Let the checker compare: a class with the wrong method name, argument list or return type is rejected at the call site, with a note that shows expected and actual.
  4. Add @runtime_checkable only if you need isinstance against the Protocol. It checks that the names exist, not the signatures.
protocol_vs_abc.py · Python 3.12runs offline
from decimal import Decimal
from typing import Protocol


class PriceRule(Protocol):
    def apply(self, subtotal: Decimal) -> Decimal: ...


class TenPercentOff:                       # no base class, no "implements"
    def apply(self, subtotal: Decimal) -> Decimal:
        return subtotal * Decimal("0.90")


class BrokenRule:
    def apply(self, subtotal: Decimal, extra: int) -> Decimal:   # wrong signature
        return subtotal


def run(rule: PriceRule, subtotal: Decimal) -> Decimal:
    return rule.apply(subtotal)


print(run(TenPercentOff(), Decimal("20.00")))
print(run(BrokenRule(), Decimal("20.00")))   # ❌ mypy rejects; runtime fails later

What you see: Python runs the first call, fails on the second only when it is reached, and the checker rejects it before.

python protocol_vs_abc.py (last lines)runs offline
18.0000
Traceback (most recent call last):
  File "/home/iam100god/Desktop/AI_COURSE/code/e19-python-deep-dive/C/protocol_vs_abc.py", line 24, in <module>
    print(run(BrokenRule(), Decimal("20.00")))   # ❌ mypy rejects; runtime fails later
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/iam100god/Desktop/AI_COURSE/code/e19-python-deep-dive/C/protocol_vs_abc.py", line 20, in run
    return rule.apply(subtotal)
           ^^^^^^^^^^^^^^^^^^^^
TypeError: BrokenRule.apply() missing 1 required positional argument: 'extra'
mypy protocol_vs_abc.pyruns offline
protocol_vs_abc.py:24: error: Argument 1 to "run" has incompatible type "BrokenRule"; expected "PriceRule"  [arg-type]
protocol_vs_abc.py:24: note: Following member(s) of "BrokenRule" have conflicts:
protocol_vs_abc.py:24: note:     Expected:
protocol_vs_abc.py:24: note:         def apply(self, subtotal: Decimal) -> Decimal
protocol_vs_abc.py:24: note:     Got:
protocol_vs_abc.py:24: note:         def apply(self, subtotal: Decimal, extra: int) -> Decimal
Found 1 error in 1 file (checked 1 source file)

At runtime, TenPercentOff worked (the first print is cut from this output) and BrokenRule failed with a TypeError for a missing argument, only when that line ran. mypy found it earlier and explained it: it printed the signature it expected (apply(self, subtotal)) next to the one it got (apply(self, subtotal, extra)). Note that TenPercentOff never mentioned PriceRule anywhere.

Java · interface (nominal)

A class counts as a rule only if it says so with implements. A class from a library you cannot edit never qualifies.

PriceRule.javaruns offline
interface PriceRule {
  Money apply(Money subtotal);
}

class TenPercentOff implements PriceRule {
  public Money apply(Money s) { ... }
}

Python · Protocol (structural)

A class counts if it has the right methods. No import, no base class, no change to the class.

rules.py · Python 3.14runs offline
class PriceRule(Protocol):
    def apply(self, subtotal: Money) -> Money:
        ...

class TenPercentOff:        # no mention of it
    def apply(self, subtotal: Money) -> Money:
        ...

The shift: Java asks "did you declare that you are one?" (the name decides). Python asks "do you have the right shape?" (the structure decides), which lets you describe a type after the fact, around code you do not own.

Typing a JSON payload: four ways, and what each one actually checks
OptionPick it whenCost or catch
TypedDictYou keep the data as a plain dict (it goes straight to json.dumps) and want the checker to know the keys.Checks nothing at run time. A string where an int belongs passes silently (see the output below).
@dataclassInternal values with behaviour: methods, defaults, frozen=True.No validation at all. The annotations are still only notes.
Pydantic BaseModelData from outside the process: HTTP bodies, files, queues. Checks and converts types on arrival.A dependency and a small cost per object. Its default mode is lax and converts "7" to 7.
attrsLike dataclass, but you want validators, converters and more control.Another dependency, and most teams get by with dataclass.

The table's claim about run-time checking is easy to test. We feed the same wrong JSON into all three kinds. The input is {"id": "7", "total_cents": "12.5"}, with both fields as strings.

typeddict_dataclass.py · Python 3.12runs offline
from dataclasses import dataclass
from typing import TypedDict


class OrderDict(TypedDict):
    id: int
    total_cents: int


@dataclass(frozen=True)
class OrderObj:
    id: int
    total_cents: int


raw = {"id": "7", "total_cents": "12.5"}          # what a JSON API really sent: wrong types

d: OrderDict = raw                                # type: ignore[assignment]
o = OrderObj(**raw)                               # type: ignore[arg-type]
print("TypedDict at runtime:", d)
print("dataclass at runtime:", o)

from pydantic import BaseModel, ValidationError


class OrderModel(BaseModel):
    id: int
    total_cents: int


try:
    OrderModel(**raw)
except ValidationError as e:
    print("pydantic at runtime:", e.errors()[0]["loc"], "-", e.errors()[0]["msg"])
print("pydantic, lax mode:", OrderModel(id="7", total_cents="125"))
output · Python 3.12.3runs offline
TypedDict at runtime: {'id': '7', 'total_cents': '12.5'}
dataclass at runtime: OrderObj(id='7', total_cents='12.5')
pydantic at runtime: ('total_cents',) - Input should be a valid integer, unable to parse string as an integer
pydantic, lax mode: id=7 total_cents=125

The TypedDict and the dataclass both accepted the wrong data and kept the strings. Pydantic refused total_cents='12.5', because 12.5 cannot become an integer, and it converted "125" to the integer 125 (its lax mode). So the rule is: the type checker protects the code you wrote, validation protects the data you did not write. Fig. 19.18 puts both next to the third net, tests.

Three nets, three kinds of bug (examples from this chapter) Static: the type checker runs before the code runs catches: ✓ rule.amount when rule is None ✓ str passed where int expected ✓ BrokenRule is not a PriceRule cannot see: ✗ JSON with wrong types ✗ 25.58 or 25.59? (logic) Runtime: Pydantic at the edge runs when the data arrives catches: ✓ '12.5' is not an integer ✓ missing or unknown fields ✓ numbers outside the range cannot see: ✗ None-access in your code ✗ wrong tax rounding Behaviour: pytest + Hypothesis runs in CI before every deploy catches: ✓ 25.58 is half-even rounding ✓ unknown code is ignored ✓ Hypothesis found (90, 90) cannot see: ✗ inputs nobody thought of ✗ data only production has
Fig. 19.18 — Static checking, runtime validation and tests catch different bugs. The type checker finds the None access before the program runs, Pydantic finds the bad JSON when it arrives, and tests find wrong behaviour that is perfectly typed.

The figure also says what no net covers alone. A type checker cannot know that 25.58 should have been 25.59, and a test cannot cover an input nobody imagined. That is why serious codebases use all three. Hypothesis, shown later, widens the third net by inventing inputs for you.

Type checkers for Python: which one, and when to switch
OptionPick it whenCost or catch
mypyThe default for most teams. The longest history, a large plug-in ecosystem, and it was used for every check on this page.Slower on big codebases than the newer tools. Its rules are strict in some places and loose in others, so configure it (strict = true in the ladder below).
pyrightYou use VS Code with Pylance (it is the engine), or you want fast checks and stronger inference.Needs Node.js to run from the command line. It and mypy sometimes disagree about edge cases.
ty (Astral)You already use Ruff and uv and want one fast toolchain. Still in beta/preview as of this writing, so check its current status before betting on it.Younger, so rules and diagnostics are still changing.

For a team adding types to an existing codebase, the choice matters less than the habit: run one checker in CI, fail the build on new errors, and tighten the settings module by module. Switch when your CI check takes minutes, or when your editor and CI disagree often enough to cost review time.

Idiom: Keep signatures with ParamSpec

The problem: pricer wraps its functions in a logging decorator. The usual untyped wrapper takes *args, **kwargs. For the checker, the decorated function now accepts anything, so every call to it is unchecked. The decorator quietly turned off typing for every function it touches.

How it works: ParamSpec (written **P) captures the parameter list of the function being wrapped, and R captures its return type. The decorator then promises to return a callable with the same parameters and result.

  1. Declare the type parameters: def logged[**P, R](fn: Callable[P, R]) -> Callable[P, R]:.
  2. Type the wrapper with the same names: def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:.
  3. Keep functools.wraps(fn) so the name and docstring survive at run time (Part B's idiom).
  4. Add or remove a first argument with Concatenate when the decorator injects a parameter (below).
typed_decorator.py · checked with mypyruns offline
import functools
from collections.abc import Callable
from typing import reveal_type


def logged_untyped(fn):                       # ❌ erases the signature
    @functools.wraps(fn)
    def wrapper(*args, **kwargs):
        return fn(*args, **kwargs)
    return wrapper


def logged[**P, R](fn: Callable[P, R]) -> Callable[P, R]:   # ✅ ParamSpec
    @functools.wraps(fn)
    def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
        print(f"calling {fn.__name__}")
        return fn(*args, **kwargs)
    return wrapper


@logged_untyped
def price_a(cents: int, qty: int = 1) -> int:
    return cents * qty


@logged
def price_b(cents: int, qty: int = 1) -> int:
    return cents * qty


reveal_type(price_a)
reveal_type(price_b)
price_a("oops")           # untyped decorator: mypy says nothing
price_b("oops")           # ✅ typed decorator: mypy catches it

Make the invisible visible: what mypy thinks each decorated function is.

mypy --python-version 3.14 typed_decorator.pyruns offline
typed_decorator.py:31: note: Revealed type is "Any"
typed_decorator.py:32: note: Revealed type is "def (cents: int, qty: int =) -> int"
typed_decorator.py:34: error: Argument 1 to "price_b" has incompatible type "str"; expected "int"  [arg-type]
Found 1 error in 1 file (checked 1 source file)

Before the idiom, price_a is revealed as Any: the checker lost the function, and line 33 (price_a("oops")) was silently accepted. After the idiom, price_b keeps its real signature, def (cents: int, qty: int = ...) -> int, and line 34 is reported as Argument 1 to "price_b" has incompatible type "str"; expected "int". Same decorator job, but now the checker still sees through it.

Concatenate handles decorators that supply the first argument themselves, such as a request-injecting decorator. The wrapper takes fewer parameters than the function it wraps.

concat_decorator.py · Python 3.14runs offline
from collections.abc import Callable
from typing import Concatenate, reveal_type


class Request:
    request_id = "r-1"


def with_request[**P, R](fn: Callable[Concatenate[Request, P], R]) -> Callable[P, R]:
    def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
        return fn(Request(), *args, **kwargs)     # injects the first argument
    return wrapper


@with_request
def price(req: Request, cents: int) -> str:
    return f"{req.request_id}: {cents}"


reveal_type(price)
print(price(250))
mypy --python-version 3.14 concat_decorator.pyruns offline
concat_decorator.py:20: note: Revealed type is "def (cents: int) -> str"
Success: no issues found in 1 source file
python concat_decorator.pyruns offline
Runtime type is 'function'
r-1: 250

The original price takes (req, cents). mypy shows the decorated one as def (cents: int) -> str, so callers write price(250), as the run printed. The request parameter has been removed from the public signature and the checker knows it. The line "Runtime type is 'function'" is what reveal_type prints when the program runs; it does nothing else at runtime.

Bridge: annotations are lazy in 3.14

One of the oldest annoyances in typed Python is the forward reference: a class annotation that names a class defined below it. On 3.12 that is an error at the moment the class body runs, because Python tried to evaluate the annotation immediately.

Python 3.12: class Order with customer: Customer, before Customer existsruns offline
Traceback (most recent call last):
  File "<string>", line 2, in <module>
  File "<string>", line 3, in Order
NameError: name 'Customer' is not defined

The workaround used to be quoting the name ("Customer") or writing from __future__ import annotations at the top of the file. In Python 3.14 (PEP 649 and PEP 749) annotations are evaluated lazily. The compiler stores a small function for them and runs it only when somebody asks. The standard library module annotationlib is how you ask, in the format you want.

deferred_annotations.py · Python 3.14runs offline
import annotationlib


class Order:
    customer: Customer            # Customer does not exist yet; no quotes needed in 3.14
    total: int


print("before Customer exists:")
print("  ", annotationlib.get_annotations(Order, format=annotationlib.Format.FORWARDREF))


class Customer:
    name: str


print("after Customer exists:")
print("  ", Order.__annotations__)
print("   as strings:", annotationlib.get_annotations(Order, format=annotationlib.Format.STRING))
output · Python 3.14.7runs offline
before Customer exists:
   {'customer': ForwardRef('Customer', is_class=True, owner=<class '__main__.Order'>), 'total': <class 'int'>}
after Customer exists:
   {'customer': <class '__main__.Customer'>, 'total': <class 'int'>}
   as strings: {'customer': 'Customer', 'total': 'int'}

The class body ran fine with no quotes. Asked while Customer still did not exist, get_annotations with the FORWARDREF format returned a placeholder, ForwardRef('Customer'), instead of crashing. After Customer was defined, the same annotation resolved to the real class. The STRING format returns the source text. For application code, the practical effect is simple: forward references just work, and libraries that inspect annotations (Pydantic, FastAPI, dataclasses) should use annotationlib.get_annotations instead of reading __annotations__ by hand on old interpreters.

Bridge: t-strings, templates that cannot inject

An f-string builds the final text at once: f"... {customer}" glues the value into the string and you cannot tell afterwards which part was yours. That is exactly how SQL injection happens when the glued value comes from a user.

Python 3.14 (PEP 750) adds template strings, written t"...". A t-string does not produce a str. It produces a Template object that keeps the fixed text and the interpolated values apart. Code you write decides how to combine them, which lets a library escape, quote or parameterise safely.

tstring_sql.py · Python 3.14runs offline
import sqlite3
from string.templatelib import Interpolation, Template

order_id = 7
customer = "x'; DROP TABLE orders; --"        # hostile input

t = t"SELECT total FROM orders WHERE id = {order_id} AND who = {customer}"
print(type(t).__name__)
for part in t:
    print("  ", type(part).__name__, repr(part if isinstance(part, str) else part.value))


def to_sql(template: Template) -> tuple[str, list]:
    sql, params = [], []
    for part in template:
        if isinstance(part, Interpolation):
            sql.append("?")                    # the value never enters the SQL text
            params.append(part.value)
        else:
            sql.append(part)
    return "".join(sql), params


sql, params = to_sql(t)
print(sql)
print(params)

db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE orders (id INTEGER, who TEXT, total INTEGER)")
db.execute("INSERT INTO orders VALUES (7, 'ana', 1250)")
print("rows:", db.execute(sql, params).fetchall())
print("f-string version would send:")
print(f"  SELECT total FROM orders WHERE id = {order_id} AND who = {customer}")
output · Python 3.14.7runs offline
Template
   str 'SELECT total FROM orders WHERE id = '
   Interpolation 7
   str ' AND who = '
   Interpolation "x'; DROP TABLE orders; --"
SELECT total FROM orders WHERE id = ? AND who = ?
[7, "x'; DROP TABLE orders; --"]
rows: []
f-string version would send:
  SELECT total FROM orders WHERE id = 7 AND who = x'; DROP TABLE orders; --

Read it from the top. type(t) is Template, and iterating gives alternating fixed strings and Interpolation objects that carry the value. The helper to_sql puts a ? placeholder in the SQL for each value and collects the values in a separate list, so the hostile input x'; DROP TABLE orders; -- never becomes part of the SQL text.

The database receives the query and the parameters separately and treats the dangerous string as plain data (zero rows matched, nothing dropped). The last two lines show what an f-string would have sent: the attack text spliced straight into the statement.

This is not magic. A t-string by itself is only a container, and nothing is safe until a function like to_sql processes it. The gain is that the safe path is now the easy path: the library takes a Template, and a plain str can be refused.

Bridge: packaging, one level down

Now Friday's incident. To understand it you need to see what an "environment" and a "dependency" physically are. Start with the folder everyone calls a virtual environment.

A virtual environment (venv) is not a virtual machine and not a container. It is a normal folder with a few files in it. Its job is to give one project its own set of installed packages, so that project A can use version 1 of a library while project B uses version 2. Fig. 19.19 shows what is inside.

What a virtual environment physically is .venv/ ├── pyvenv.cfg (1) ├── bin/ │ ├── python -> /usr/bin/python3.12 (2) │ ├── python3, python3.12 -> python │ └── pytest, mypy, pip (scripts) (3) ├── lib/python3.12/site-packages/ (4) │ ├── httpx/ httpx-0.28.1.dist-info/ │ └── anyio/ idna/ h11/ ... └── include/ (1) pyvenv.cfg: home = /usr/bin says where the real interpreter lives; version_info = 3.12.3; include-system-site-packages = false (2) bin/python is only a symlink. Python finds the pyvenv.cfg next to it and moves its package paths to this folder. (3) Launcher scripts: their first line names this venv's python, so running pytest uses these packages and no others. (4) site-packages is the whole environment. Delete it and the packages are gone; the interpreter itself was never inside the venv.
Fig. 19.19 — A venv is a folder: a config file, a symlink to a shared interpreter, launcher scripts, and a site-packages directory holding the installed packages.

You can read the real thing. This is the course's own environment, and then the one that uv made for the demo project below.

cat .venv/pyvenv.cfg (the course venv)runs offline
home = /usr/bin
implementation = CPython
uv = 0.12.5
version_info = 3.12.3
include-system-site-packages = true
cat .venv/pyvenv.cfg (a uv project venv)runs offline
home = /usr/bin
implementation = CPython
uv = 0.12.5
version_info = 3.12.3
include-system-site-packages = false
prompt = quickbite-pricer

Look at home = /usr/bin. The environment does not contain Python. It points at an interpreter that lives elsewhere. The other difference is include-system-site-packages: the course venv is true, so it can also see packages installed system-wide, and the uv project venv is false, a sealed room. A sealed venv is the safer default, because a package that happens to be installed on the machine cannot sneak into your project and hide a missing dependency.

"Activating" a venv does only one thing: it puts the venv's bin folder first on your shell's PATH. You do not need to activate at all if you call .venv/bin/python directly, which is what scripts and CI should do.

Bridge: what goes in pyproject.toml, and what a build backend is

pyproject.toml is the one file that describes a Python project. It has three jobs, in three tables.

The point of the split is that the installer (pip, uv) and the builder (hatchling) are separate programs that talk through a standard interface. You can change the backend without changing how anyone installs your project.

Wheel versus sdist. A library is shipped in two forms. An sdist (source distribution) is a tarball of your source; installing it means building it on the user's machine, which for a package with C code means running a compiler. A wheel (.whl) is a ready-built zip that is simply unpacked into site-packages.

Its file name says which Python and platform it was built for, such as cp312-manylinux_x86_64. If a wheel exists for your platform, installing is fast and needs no compiler. If not, the installer falls back to the sdist and compiles, which is why some installs suddenly want a C toolchain.

The src layout. Put the package at src/pricer/ and not at pricer/ beside the tests. With the flat layout, running pytest from the project root imports your source folder directly, so tests can pass against files that never get installed. With src/ the package is only importable once it is installed (or pointed to), so the tests exercise what users will get. Missing files, such as a forgotten data file, show up as test failures instead of as production bugs.

Idiom: Lock every dependency, and install from the lock

The problem: your pyproject.toml says httpx>=0.28.1. That is a range, not a version. Every fresh install resolves the range to whatever is newest today, for httpx and for each library it pulls in (its transitive dependencies). Friday's build and Tuesday's build were different programs with the same source.

How it works: a lockfile records the exact version and the file hash of every package in the whole tree. Installing from the lock reproduces the same environment on every machine, and fails loudly if a downloaded file does not match its hash. Java readers know this from Gradle's dependency-locking or Maven's pinned versions plus a checksum.

  1. Declare ranges in pyproject.toml: what you need and the oldest version you support. uv add httpx writes the line for you.
  2. Resolve once into uv.lock: uv lock (run by uv add too) picks exact versions for the whole tree and writes hashes. Commit this file.
  3. Install from the lock everywhere else: uv sync --frozen in CI and in the Docker build. --frozen means "use the lock as it is, do not re-resolve". --locked is similar but fails if the lock is out of date with pyproject.toml.
  4. Upgrade on purpose: uv lock --upgrade-package httpx in its own pull request, with tests, so a library update is a visible change in version control.

The setup: a tiny project made with uv init --lib, with one dependency. This needs the network once, to read the package index.

uv init and uv add (one dependency, eight packages)runs offline
$ uv init --lib --name quickbite-pricer .
Initialized project `quickbite-pricer` at `.../C/uvdemo`
$ uv add httpx
Using CPython 3.12.3 interpreter at: /usr/bin/python3.12
Creating virtual environment at: .venv
Resolved 8 packages in 566ms
Prepared 3 packages in 280ms
Installed 8 packages in 7ms
 + anyio==4.16.0
 + certifi==2026.11.20
 + h11==0.16.0
 + httpcore==1.0.9
 + httpx==0.28.1
 + idna==3.20
 + quickbite-pricer==0.1.0 (from file:///.../C/uvdemo)
 + typing-extensions==4.16.0
pyproject.toml (after uv add)runs offline
[project]
name = "quickbite-pricer"
version = "0.1.0"
description = "pricer, packaged with uv"
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
    "httpx>=0.28.1",
]

[build-system]
requires = ["uv_build>=0.12.5,<0.13.0"]
build-backend = "uv_build"

We asked for one library. uv installed eight packages, because httpx needs httpcore, which needs h11, and so on. Here are the exact versions written into uv.lock for one of them, with the long download URLs cut.

uv.lock (excerpt: the httpx entry; URLs and hashes cut at 100 characters)runs offline
version = 1
revision = 3
requires-python = ">=3.12"


[[package]]
name = "httpx"
version = "0.28.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
    { name = "anyio" },
    { name = "certifi" },
    { name = "httpcore" },
    { name = "idna" },
]
sdist = { url = "https://files.pythonhosted.org/packages/b1/df/48c586a5fe32a0f01324ee087459e112eb...
wheels = [
    { url = "https://files.pythonhosted.org/packages/2a/39/e50c7c3a983047577ee07d2a9e53faf5a69493...
]
uv sync --frozen, then uv treeruns offline
Using CPython 3.12.3 interpreter at: /usr/bin/python3.12
Creating virtual environment at: .venv
Installed 8 packages in 7ms
 + anyio==4.16.0
 + certifi==2026.11.20
 + h11==0.16.0
 + httpcore==1.0.9
 + httpx==0.28.1
 + idna==3.20
 + quickbite-pricer==0.1.0 (from file://.../C/uvdemo)
 + typing-extensions==4.16.0
Resolved 8 packages in 2ms
quickbite-pricer v0.1.0
└── httpx v0.28.1
    ├── anyio v4.16.0
    │   ├── idna v3.20
    │   └── typing-extensions v4.16.0
    ├── certifi v2026.11.20
    ├── httpcore v1.0.9
    │   ├── certifi v2026.11.20
    │   └── h11 v0.16.0
    └── idna v3.20

The tree shows who pulled in whom. idna is needed twice (by httpx and by anyio) and appears once in the lock, at one version. Had Friday's build run from a lockfile, it would have installed exactly Tuesday's versions, and the surprise minor release would have waited for a pull request.

Dependency and environment tools: which one, and when to switch
OptionPick it whenCost or catch
uvNew projects and teams that want one fast tool: Python versions, venvs, lockfile, build and run. Used for the demo above.Newer than pip, so some corporate tooling still assumes requirements.txt. It can export one.
pip + pip-toolsYou must stay on stock tooling. pip-compile writes a pinned requirements.txt with hashes.Two tools and a manual workflow. It does not install Python itself and is slower.
PoetryYou already have it, and like its all-in-one publishing and groups.Its own lock format, and some of its settings differ from the standard [project] table (newer versions follow it more closely, so check the current docs).
PDMYou want a standards-first manager with a lockfile and PEP 621 metadata.A smaller community than Poetry or uv.
condaNative libraries are the hard part: CUDA, GDAL, scientific stacks with system libraries.A separate world with its own channels and slower solves. Mixing it with pip needs care.

Switch tools for a reason you can name. "pip is too slow in CI" (minutes on a large lock) or "we need Python itself pinned per project" both justify uv. "Our model needs a specific CUDA build" justifies conda. "It is fashionable" does not justify anything.

Bridge: Ruff, lint and format in one fast tool

Ruff is a linter (finds likely bugs and style problems) and a formatter (rewrites code into one standard layout) in a single program written in Rust. It replaces flake8, isort and black in most projects, and runs on a large codebase in a fraction of a second. We ran it with uvx ruff, which downloads and runs it without installing it into the project (needs the network the first time).

ruff_demo.py (deliberately messy)runs offline
import os, sys
from decimal import Decimal

def total( items ):
    t=0
    for i in items :
        t = t+ i
    unused = Decimal("1")
    return t
uvx ruff check --output-format concise ruff_demo.pyruns offline
ruff_demo.py:1:1: I001 [*] Import block is un-sorted or un-formatted
ruff_demo.py:1:8: F401 [*] `os` imported but unused
ruff_demo.py:1:12: F401 [*] `sys` imported but unused
ruff_demo.py:8:5: F841 Local variable `unused` is assigned to but never used
ruff_demo.py:8:22: FURB157 [*] Verbose expression in `Decimal` constructor
Found 5 errors.
[*] 4 fixable with `--fix` (1 unsafe fix available with `--fix --unsafe-fixes`).
uvx ruff format --diff ruff_demo.pyruns offline
--- ruff_demo.py
+++ ruff_demo.py
@@ -1,9 +1,10 @@
 import os, sys
 from decimal import Decimal
 
-def total( items ):
-    t=0
-    for i in items :
-        t = t+ i
+
+def total(items):
+    t = 0
+    for i in items:
+        t = t + i
     unused = Decimal("1")
     return t

1 file would be reformatted

The checker found five things: unsorted imports, two unused imports (os and sys), an unused local variable, and a small simplification of the Decimal call. Four are fixable automatically with --fix. The formatter shows what it would change, mostly spaces. We also ran both on the finished pricer package below, and it passes (the ladder shows the result).

The team habit is: format on save, run ruff check and the type checker in CI, and never argue about style in a review again.

Bridge: pytest, one level down

pytest finds functions named test_*, runs them, and treats a plain assert as the check. When an assert fails, pytest rewrites it to show both sides, which is why you rarely need assertEqual. The feature that makes pytest scale, though, is the fixture.

A fixture is a function that builds something a test needs (a basket, a database connection, a temporary folder). A test asks for it simply by naming it as a parameter. pytest sees the name, runs the fixture first, and passes in the result. A fixture that uses yield hands the value to the test and resumes after the test to clean up, so setup and teardown live in one place.

Two settings decide how fixtures behave. Scope says how long the value lives: function (a fresh one per test, the default), module, or session (one for the whole run, good for an expensive database connection). conftest.py is a special file: fixtures defined in it are available to every test in its folder and below, with no import.

The setup: a session fixture db, a function fixture cart that uses it, and two tests. We print from the fixtures (with -s) to see the order.

test_fixture_order.py · Python 3.12runs offline
import pytest


@pytest.fixture(scope="session")
def db():
    print("\n  [session] open database")
    yield "db-connection"
    print("\n  [session] close database")


@pytest.fixture
def cart(db):
    print(f"\n  [function] new cart using {db}")
    cart = []
    yield cart
    print(f"\n  [function] teardown cart, it held {cart}")


def test_add_pizza(cart):
    cart.append("pizza")


def test_cart_is_fresh_each_time(cart):
    assert cart == []          # the previous test's pizza is gone
pytest -q -s test_fixture_order.pyruns offline

  [session] open database

  [function] new cart using db-connection
.
  [function] teardown cart, it held ['pizza']

  [function] new cart using db-connection
.
  [function] teardown cart, it held []

  [session] close database

2 passed in 0.11s

The database opened once, before the first test, and closed once, after the last. The cart was built and torn down around each test separately. The second test saw an empty cart, even though the first one added a pizza, because each test got its own. The teardown line even shows what the first cart held (['pizza']), which is a handy place for cleanup that depends on what the test did.

Idiom: Build test data with fixtures, not shared globals

The problem: tests that build their data at the top of the module, or share one mutable list, pass alone and fail together, because one test's changes leak into the next. Or each test repeats ten lines of setup, and nobody notices when a copy goes stale.

How it works: put the setup in a fixture with the narrowest scope that is still fast enough. The default (a new one per test) removes shared state by construction. Widen the scope only for expensive, read-only things.

  1. Write the fixture once in conftest.py, returning a fresh object each time (a new list, a new RuleBook).
  2. Request it by parameter name: def test_x(basket, book):. No imports, no setup lines.
  3. Use yield for cleanup: close connections or delete files after the yield, so cleanup runs even when the test fails. For files, prefer the built-in tmp_path fixture, which pytest creates and removes for you.
  4. Widen the scope with care: scope="session" only for objects tests never change. Never for a list that tests append to.

The pricer package in the next part has exactly this shape: conftest.py builds book and basket fresh for every test, and test_service.py just names them. Also look at parametrize there: one test function with four rows of input and expected output, which pytest runs as four tests with separate names.

Idiom: Patch the name where it is used

The problem: you replace a slow or random function with a fake using unittest.mock.patch, and the test behaves as if you had not. You patch pricer.rates.fetch_tax_rate, where the function is defined, but the code under test still calls the real one.

How it works: from pricer.rates import fetch_tax_rate in service.py copies the reference into service's own namespace. Now two names point at the same function: pricer.rates.fetch_tax_rate and pricer.service.fetch_tax_rate. patch rebinds one name. The code under test looks up the name in its own module, so you must replace that one.

  1. Find the line in the code under test that uses the thing: fetch_tax_rate(region) in service.py.
  2. Check how it got there: from x import y means patch "module_under_test.y". import x then x.y() means patch "x.y".
  3. Prefer monkeypatch.setattr (undone automatically) or pass the dependency in as a parameter, so the test needs no patching at all.
test_patch_wrong.py · Python 3.12runs offline
from decimal import Decimal
from unittest.mock import patch

from pricer.money import Money
from pricer.service import LineItem, price_order
from pricer.rules import RuleBook

ITEMS = [LineItem("pizza", Money.of("9.50"), 2), LineItem("cola", Money.of("2.50"), 1)]


def test_patch_the_definition():                 # ❌ service.py did: from pricer.rates import fetch_tax_rate
    with patch("pricer.rates.fetch_tax_rate", return_value=Decimal("0.00")):
        assert price_order(ITEMS, RuleBook([])) == Money.of("21.50")


def test_patch_where_it_is_used():               # ✅
    with patch("pricer.service.fetch_tax_rate", return_value=Decimal("0.00")):
        assert price_order(ITEMS, RuleBook([])) == Money.of("21.50")

Make the invisible visible: the same test, patched in the wrong place and in the right place.

pytest -q test_patch_wrong.pyruns offline
F.                                                                       [100%]
=================================== FAILURES ===================================
__________________________ test_patch_the_definition ___________________________
    def test_patch_the_definition():                 # ❌ service.py did: from pricer.rates import fetch_tax_rate
        with patch("pricer.rates.fetch_tax_rate", return_value=Decimal("0.00")):
>           assert price_order(ITEMS, RuleBook([])) == Money.of("21.50")
E           AssertionError: assert Money(amount=...urrency='EUR') == Money(amount=...urrency='EUR')
E             
E             Omitting 1 identical items, use -vv to show
E             Differing attributes:
E             ['amount']
E             
E             Drill down into differing attribute amount:
E               amount: Decimal('25.58') != Decimal('21.50')
test_patch_wrong.py:13: AssertionError
=========================== short test summary info ============================
FAILED test_patch_wrong.py::test_patch_the_definition - AssertionError: asser...
1 failed, 1 passed in 0.16s

The first test failed, with the real tax rate still applied: Decimal('25.58') != Decimal('21.50'). 25.58 is 21.50 plus 19 percent tax and rounding, so the real fetch_tax_rate ran. Patching pricer.rates.fetch_tax_rate changed a name that service.py never looks at. The second test, with the patch on pricer.service.fetch_tax_rate, passed. (In the ladder's own test file, the wrong-place test is written the other way round, asserting the "still taxed" value, so the whole suite stays green and the lesson stays in the code.)

Bridge: property-based testing with Hypothesis

A normal test checks the examples you thought of. Hypothesis instead checks a property, a sentence that should hold for all inputs ("the discount equals the integer formula"), against hundreds of inputs it generates itself. When it finds a failing one, it shrinks it: it searches for the smallest, simplest input that still fails, so the report is readable.

Below is a deliberately buggy discount function that uses floating-point arithmetic. The property compares it with exact integer arithmetic.

test_hypothesis_bug.py · Python 3.12runs offline
from hypothesis import given, settings
from hypothesis import strategies as st


def apply_percent(cents: int, percent: int) -> int:
    return int(cents * (1 - percent / 100))         # float maths


@settings(derandomize=True)        # same examples every run, so CI is not flaky
@given(st.integers(0, 10_000), st.integers(0, 100))
def test_discount_matches_integer_maths(cents, percent):
    expected = cents * (100 - percent) // 100
    assert apply_percent(cents, percent) == expected
pytest -q test_hypothesis_bug.pyruns offline
F                                                                        [100%]
=================================== FAILURES ===================================
_____________________ test_discount_matches_integer_maths ______________________
    @settings(derandomize=True)        # same examples every run, so CI is not flaky
>   @given(st.integers(0, 10_000), st.integers(0, 100))
                   ^^^
test_hypothesis_bug.py:10: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
cents = 90, percent = 90
    @settings(derandomize=True)        # same examples every run, so CI is not flaky
    @given(st.integers(0, 10_000), st.integers(0, 100))
    def test_discount_matches_integer_maths(cents, percent):
        expected = cents * (100 - percent) // 100
>       assert apply_percent(cents, percent) == expected
E       assert 8 == 9
E        +  where 8 = apply_percent(90, 90)
E       Failing test case: test_discount_matches_integer_maths(
E           cents=90,
E           percent=90,
E       )
test_hypothesis_bug.py:13: AssertionError
=========================== short test summary info ============================
FAILED test_hypothesis_bug.py::test_discount_matches_integer_maths - assert 8...
1 failed in 0.32s

Hypothesis reported cents=90, percent=90: a 90 percent discount on 90 cents should leave 9 cents, and the function returned 8. The cause is that 1 - 90/100 is not exactly 0.1 in binary floating point, so the product is a hair below 9 and int() cuts it down to 8. No example I would have written by hand would have found this; the generator found it quickly and shrank it to the smallest failing pair it could.

The derandomize=True setting makes the run use the same examples every time. Without it, a rare bug may be found on one CI run and missed on the next, which is useful in a nightly job and annoying in a merge gate. Hypothesis also remembers failing examples in a local database, so a bug it found once is replayed first on later runs.

I found, while preparing this page, that on an earlier version of this test with a much rarer failure (about 1 in 150 inputs) one run passed and the next failed, which is exactly the reason for the setting. The pricer package uses a gentler property, "money addition commutes", as a real example.

Bridge: the performance workflow

Now the last tool on the list, the one that most often goes wrong, because it needs patience. Performance work has one rule: measure first, change one thing, measure again. A fix that was not preceded by a measurement is a guess. Here is the whole loop on pricer.

The story: an endpoint that checks discount codes becomes slow as the code list grows. Someone suggests rewriting it in another language. Before agreeing, we measure.

The setup: 2,000 known codes stored in a list, and 4,000 incoming orders, half with unknown codes. The slow function checks code in CODES. We time it, profile it, fix it and time it again.

slow_pricer.py · Python 3.14runs offline
import cProfile
import pstats
import time

CODES = [f"CODE{i}" for i in range(2000)]          # known discount codes (a list)
ORDERS = [f"CODE{(i * 7) % 4000}" for i in range(4000)]   # half of them unknown


def is_valid_slow(code):
    return code in CODES                # ❌ scans the list: O(n) per lookup


def count_valid_slow(orders):
    return sum(1 for code in orders if is_valid_slow(code))


def count_valid_fast(orders):
    known = set(CODES)                  # ✅ hash lookup: O(1)
    return sum(1 for code in orders if code in known)


def price_all(orders):
    return count_valid_slow(orders), len(orders)


t = time.perf_counter()
price_all(ORDERS)
print(f"plain run: {time.perf_counter() - t:.3f} s\n")

prof = cProfile.Profile()
prof.runcall(price_all, ORDERS)
pstats.Stats(prof).sort_stats("tottime").print_stats(2)

t = time.perf_counter()
count_valid_fast(ORDERS)
print(f"after the fix: {time.perf_counter() - t:.4f} s")
assert count_valid_slow(ORDERS) == count_valid_fast(ORDERS)
output · Python 3.14.7runs offline
# measured on the course machine (12 cores); your numbers will differ
plain run: 0.044 s

         6006 function calls in 0.061 seconds

   Ordered by: internal time
   List reduced from 7 to 2 due to restriction <2>

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
     4000    0.050    0.000    0.050    0.000 /home/iam100god/Desktop/AI_COURSE/code/e19-python-deep-dive/C/slow_pricer.py:9(is_valid_slow)
     2001    0.008    0.000    0.058    0.000 /home/iam100god/Desktop/AI_COURSE/code/e19-python-deep-dive/C/slow_pricer.py:14(<genexpr>)


after the fix: 0.0004 s

Step by step. The plain run took 0.044 s. Under cProfile the total is higher (0.061 s), because the profiler adds its own cost to every function call. That is normal: use the profile to compare functions with each other, and use timeit or a plain run for the real duration.

The profile sorted by tottime (time spent inside the function itself, not in the functions it calls) puts is_valid_slow first: 4,000 calls, 0.050 s of the 0.061 s, about 82 percent. The generator expression is a distant second. We now know where to look, which is the whole point.

The fix is one line: build set(CODES) once and test membership in that. The answer is unchanged (the script asserts it), and the time dropped from 0.044 s to 0.0004 s, roughly 110 times faster. No rewrite, no other language. Fig. 19.20 shows the loop with these numbers.

The profile-first loop, with the numbers from slow_pricer.py 1 · Measure plain run: 0.044 s for 4,000 orders (this is the number to beat) 2 · Find the hot spot cProfile: is_valid_slow, 0.050 s of 0.061 s 82 percent of the time, 4,000 calls 3 · Fix one thing known = set(CODES): hash lookup, not a scan of a 2,000-item list 4 · Measure again 0.0004 s: about 110 times faster and the answers are still equal (assert) still too slow? go round again Never skip step 1 or step 2: an unmeasured fix is a guess.
Fig. 19.20 — Measure, find the hot spot, change one thing, measure again. Here the profile pointed at one function that scanned a list; replacing the list with a set made the same job about 110 times faster.

One caution about what cProfile shows: it counts function calls. The expensive work, the scan of the list, happens inside the in operator, which is not a function call, so the profile blames is_valid_slow as a whole and not the line. Knowing which line, or which operation, is a reading skill, not a tool feature.

Why is the set so much faster? A list membership test compares your value with each element in turn: its cost grows with the list (O(n)). A set computes a hash of your value and jumps straight to the right bucket (O(1) on average). The difference grows with size, so measure at two sizes.

list_vs_set.py · Python 3.14runs offline
import timeit

for n in (1_000, 100_000):
    as_list = list(range(n))
    as_set = set(as_list)
    missing = -1                                  # worst case: scan everything
    reps = 2000 if n == 1_000 else 200
    tl = timeit.timeit(lambda: missing in as_list, number=reps) / reps
    ts = timeit.timeit(lambda: missing in as_set, number=reps) / reps
    print(f"n={n:>7,}  list: {tl * 1e6:9.2f} us   set: {ts * 1e6:6.3f} us   ratio {tl / ts:8,.0f}x")
output · Python 3.14.7runs offline
# worst case for the list: the value is not there
n=  1,000  list:      5.07 us   set:  0.031 us   ratio      163x
n=100,000  list:    508.85 us   set:  0.050 us   ratio   10,119x

With 1,000 elements the set is about 170 times faster. With 100,000 elements, a hundred times more data, the list took 540 microseconds (about 100 times longer than before) while the set took 0.05 µs (still a few hundredths of a microsecond). That is the meaning of O(n) against O(1), in measured numbers: the list gets slower as the data grows and the set does not.

A second classic is building a big string in a loop.

join_vs_concat.py · Python 3.14runs offline
import timeit

parts = ["line %d" % i for i in range(20_000)]


def concat():
    s = ""
    for p in parts:
        s += p
    return s


def joined():
    return "".join(parts)


for name, fn in (("s += p", concat), ("''.join(parts)", joined)):
    t = timeit.timeit(fn, number=20) / 20
    print(f"{name:<16}{t * 1000:8.3f} ms")
output · Python 3.14.7runs offline
s += p             0.781 ms
''.join(parts)     0.103 ms

''.join(parts) is about eight times faster here. Each s += p may copy the whole string so far; join measures all the parts first and builds the result once. Be careful with this claim: CPython has a special case that sometimes makes += on a string fast, but it depends on the reference count of the string and is not a promise, so the rule remains "use join".

Idiom: Profile first, then change one thing

The problem: the endpoint is slow, and the team's guess is "Python is slow, rewrite it", or "add caching", or "use more workers". Each guess is plausible. None of them is based on where the time goes.

How it works: you pick the measurement tool by what you can reach and what question you ask.

  1. Time a small piece: timeit for a statement, or time.perf_counter() around a call. Always repeat; the first run is often different.
  2. Profile the whole run: cProfile + pstats (built in, deterministic, adds overhead) tells you which functions to look at.
  3. Profile a live process: a sampling profiler looks at the stack every millisecond or so and counts. Overhead is tiny, so you can use it on production. py-spy (a separate tool) does this for any Python version. Python 3.15 ships its own, called Tachyon, in the profiling.sampling package.
  4. Change one thing, then repeat step 1. Keep the old number written down.

Here is Tachyon on Python 3.15 (3.15.0rc1 on this machine), profiling a run of the same slow function. The real command-line entry point is python -m profiling.sampling run with an output format flag; I used --pstats to get a table like cProfile's.

tachyon_target.py · Python 3.15runs offline
CODES = [f"CODE{i}" for i in range(20000)]
ORDERS = [f"CODE{(i * 7) % 40000}" for i in range(4000)]


def is_valid_slow(code):
    return code in CODES


def main():
    return sum(1 for code in ORDERS if is_valid_slow(code))


for _ in range(2):
    main()
print("done")
python3.15 -m profiling.sampling run --pstats -l 3 --no-summary tachyon_target.pyruns offline
# colour codes stripped; 1,000 samples per second
done
Captured 971 samples in 0.97 seconds
Sample rate: 1,000.00 samples/sec
Error rate: 1.65
Profile Stats:
       nsamples   sample%  tottime (ms)    cumul%  cumtime (ms)  filename:lineno(function)
        951/951      99.6       951.000      99.6       951.000  tachyon_target.py:6(is_valid_slow)
            3/3       0.3         3.000       0.3         3.000  tachyon_target.py:1(<module>)
          1/952       0.1         1.000      99.7       952.000  tachyon_target.py:10(main.<locals>.<genexpr>)

Legend:
  nsamples: Direct/Cumulative samples (direct executing / on call stack)
  sample%: Percentage of total samples this function was directly executing
  tottime: Estimated total time spent directly in this function
  cumul%: Percentage of total samples when this function was on the call stack
  cumtime: Estimated cumulative time (including time in called functions)
  filename:lineno(function): Function location and name

It took 971 samples in 0.97 seconds, and 99.6 percent of them were inside is_valid_slow: the same answer cProfile gave, from a method that does not instrument every call. The "error rate" line tells you how many samples could not be read cleanly, a few percent here. The big feature is the second command, python -m profiling.sampling attach <pid>, which attaches to a process that is already running, without restarting it.

I tried it here, and the operating system refused: attaching needs permission to read another process's memory (the ptrace capability), which this sandbox did not grant. That is normal on locked-down servers and containers, so plan for it: grant the capability, or run the profiler as the same user with the right setting, before the day you need it. I did not test py-spy, since it is not installed here; it works the same way and needs the same permission.

When the hot spot is real Python: going native, in order of effort
OptionPick it whenCost or catch
A better algorithm or data structureAlways first. The set in the demo gave about 110 times with no new tools.Needs a profile to find, and some thought.
numpyThe loop is arithmetic over arrays of numbers. Replace the Python loop with one array operation.Data must fit arrays. Row-by-row logic with branches is a poor fit.
numbaA numeric loop you cannot express as array operations, and you want a one-line decorator, @njit.Supports a subset of Python and numpy. First call compiles. Another runtime dependency.
CythonYou have a mid-sized hot module and want C speed with Python-like syntax.A build step, and typed code is less readable.
Rust with PyO3 and maturinA hot, well-defined core (parsing, hashing, pricing rules) used by many services, and your team can maintain Rust. Memory safety without a garbage collector.A second language in the codebase, build and release complexity, and a cost for crossing the Python/Rust boundary.

Move down this table only as far as the measurement forces you. Most Python performance work ends on the first row.

Build pricer in chunks

We build a small, typed, tested package with no runtime dependencies. It uses everything in this section: a frozen Decimal value, a Protocol, a generic class, a handled None, fixtures, parametrize, Hypothesis and a correct patch. Each chunk runs on its own; the whole package comes at the end. It lives in code/e19-python-deep-dive/C/pricer/.

  1. Chunk 1 — describe the project

    Everything else hangs on this file. It names the package, says which Python it needs, lists the dev tools, and configures pytest and mypy, so the next chunks need no extra setup.

    Step-by-step: what this chunk does, in plain English
    1. [build-system] says hatchling builds the package.
    2. [project] gives the name, version and requires-python = ">=3.12". There are no runtime dependencies.
    3. [project.optional-dependencies] dev lists pytest, hypothesis and mypy.
    4. [tool.pytest.ini_options] adds src to the import path, so tests find the package without installing it.
    5. [tool.mypy] strict = true turns on the strictest checks.
    pyproject.toml — chunk 1runs offline
    [build-system]
    requires = ["hatchling"]
    build-backend = "hatchling.build"
    
    [project]
    name = "pricer"
    version = "0.1.0"
    description = "QuickBite order pricing: typed, tested, no runtime dependencies"
    requires-python = ">=3.12"
    dependencies = []
    
    [project.optional-dependencies]
    dev = ["pytest>=9", "hypothesis", "mypy"]
    
    [tool.hatch.build.targets.wheel]
    packages = ["src/pricer"]
    
    [tool.pytest.ini_options]
    pythonpath = ["src"]
    testpaths = ["tests"]
    
    [tool.mypy]
    strict = true
    files = ["src", "tests"]
    mypy_path = "src"

    [project] and [tool.*] tables (PEP 621); src layout.

    from the pricer folder, read the file with tomllib. It prints the name, the minimum Python and the dev tools.

    output · Python 3.12.3runs offline
    pricer >=3.12 ['pytest>=9', 'hypothesis', 'mypy']
  2. Chunk 2 — an exact, immutable Money

    Prices are money, and money must not be a float. This chunk builds the value object that the rest of the package passes around.

    Step-by-step: what this chunk does, in plain English
    1. @dataclass(frozen=True, slots=True) makes an immutable, hashable, small-memory class.
    2. amount is a Decimal, never a float, so 0.10 + 0.20 is exactly 0.30.
    3. Money.of("9.50") builds one from text and rounds to cents with half-even rounding.
    4. __add__ refuses to mix currencies; times multiplies and rounds.
    src/pricer/money.py — chunk 2runs offline
    from dataclasses import dataclass
    from decimal import ROUND_HALF_EVEN, Decimal
    
    CENT = Decimal("0.01")
    
    
    @dataclass(frozen=True, slots=True)
    class Money:
        """An amount of one currency. Immutable, hashable, exact."""
    
        amount: Decimal
        currency: str = "EUR"
    
        @classmethod
        def of(cls, text: str, currency: str = "EUR") -> "Money":
            return cls(Decimal(text).quantize(CENT, ROUND_HALF_EVEN), currency)
    
        def __add__(self, other: "Money") -> "Money":
            if self.currency != other.currency:
                raise ValueError(f"cannot add {self.currency} and {other.currency}")
            return Money(self.amount + other.amount, self.currency)
    
        def times(self, factor: Decimal | int) -> "Money":
            return Money(
                (self.amount * factor).quantize(CENT, ROUND_HALF_EVEN), self.currency
            )
    
        def __str__(self) -> str:
            return f"{self.amount} {self.currency}"

    frozen=True, slots=True from Section 02, and Decimal.quantize with ROUND_HALF_EVEN.

    from the pricer folder run Python with PYTHONPATH=src and add two Money values. You should see exact cents, a FrozenInstanceError on assignment, and a Money used as a dict key.

    output · Python 3.12.3runs offline
    0.30 EUR
    FrozenInstanceError
    usable as a dict key
  3. Chunk 3 — rules as a Protocol, a generic rule book

    Now the part that changes between customers: discount rules. The Protocol lets any class with the right shape be a rule, and the rule book's find returns None when a code is unknown.

    Step-by-step: what this chunk does, in plain English
    1. PriceRule(Protocol) lists name and apply.
    2. PercentOff and FlatOff are frozen dataclasses. Neither mentions PriceRule.
    3. RuleBook[R: PriceRule] is a generic class (3.12 syntax), bounded by the Protocol.
    4. find is typed R | None, so the checker makes every caller deal with a missing code.
    src/pricer/rules.py — chunk 3runs offline
    from collections.abc import Iterable
    from dataclasses import dataclass
    from decimal import Decimal
    from typing import Protocol
    
    from pricer.money import Money
    
    
    class PriceRule(Protocol):
        """Anything with a name and an apply() method is a rule. No base class needed."""
    
        @property
        def name(self) -> str: ...
    
        def apply(self, subtotal: Money) -> Money:
            """Return the subtotal after the rule."""
            ...
    
    
    @dataclass(frozen=True, slots=True)
    class PercentOff:
        name: str
        percent: Decimal
    
        def apply(self, subtotal: Money) -> Money:
            return subtotal.times(1 - self.percent / 100)
    
    
    @dataclass(frozen=True, slots=True)
    class FlatOff:
        name: str
        off: Money
    
        def apply(self, subtotal: Money) -> Money:
            left = subtotal.amount - self.off.amount
            return Money(max(left, Decimal("0.00")), subtotal.currency)
    
    
    class RuleBook[R: PriceRule]:
        """A lookup of rules by code. find() says honestly that it may find nothing."""
    
        def __init__(self, rules: Iterable[R]) -> None:
            self._by_name = {r.name: r for r in rules}
    
        def find(self, name: str) -> R | None:
            return self._by_name.get(name)
    
        def __len__(self) -> int:
            return len(self._by_name)

    Protocol and the class-level type parameter [R: PriceRule] (PEP 695).

    apply a 50 percent rule and a 5.00 flat rule to 21.50, then ask an empty-ish book for a code it does not have.

    output · Python 3.12.3runs offline
    10.75 EUR
    16.50 EUR
    None 1
  4. Chunk 4 — the service, with the None case handled

    Tuesday's incident lives here. price_order calls find, and the if rule is not None branch is what the checker demands. The tax rate comes from rates.py, which stands in for an HTTP call.

    Step-by-step: what this chunk does, in plain English
    1. LineItem is another frozen dataclass: sku, unit price, quantity.
    2. subtotal adds up the lines with exact money arithmetic.
    3. price_order applies the code only if it is given and known, then adds tax.
    4. fetch_tax_rate is imported by name with from ... import, which matters for the patch test in chunk 6.
    src/pricer/rates.py — chunk 4runs offline
    from decimal import Decimal
    
    _RATES = {"DE": Decimal("0.19"), "FR": Decimal("0.20"), "ES": Decimal("0.21")}
    
    
    def fetch_tax_rate(region: str) -> Decimal:
        """Stands in for an HTTP call to a tax service."""
        return _RATES[region]
    src/pricer/service.py — chunk 4runs offline
    from collections.abc import Sequence
    from dataclasses import dataclass
    from decimal import Decimal
    
    from pricer.money import Money
    from pricer.rates import fetch_tax_rate
    from pricer.rules import PriceRule, RuleBook
    
    
    @dataclass(frozen=True, slots=True)
    class LineItem:
        sku: str
        unit_price: Money
        qty: int
    
    
    def subtotal(items: Sequence[LineItem]) -> Money:
        total = Money(Decimal("0.00"))
        for item in items:
            total = total + item.unit_price.times(item.qty)
        return total
    
    
    def price_order(
        items: Sequence[LineItem],
        book: RuleBook[PriceRule],
        code: str | None = None,
        region: str = "DE",
    ) -> Money:
        """Subtotal, then the discount code (if any and known), then tax."""
        amount = subtotal(items)
        if code is not None:
            rule = book.find(code)
            if rule is not None:  # the checker forces this branch
                amount = rule.apply(amount)
        return amount.times(1 + fetch_tax_rate(region))

    narrowing: after if rule is not None the checker knows rule is a rule.

    price the sample basket with no code, with FIRST50, and with a typo. The typo must price like no code.

    output · Python 3.12.3runs offline
    25.58 EUR
    12.79 EUR
    25.58 EUR
  5. Chunk 5 — fixtures and unit tests

    The package works, so now we make that permanent. conftest.py builds a fresh rule book and basket for every test, and the tests for money and rules use parametrize and a Hypothesis property.

    Step-by-step: what this chunk does, in plain English
    1. @pytest.fixture functions return new objects each time.
    2. test_rules runs four input rows through one function with parametrize.
    3. test_money_is_immutable_and_hashable checks the frozen behaviour from chunk 2.
    4. test_addition_commutes is a Hypothesis test: it generates the numbers.
    tests/conftest.py — chunk 5runs offline
    from decimal import Decimal
    
    import pytest
    
    from pricer.money import Money
    from pricer.rules import FlatOff, PercentOff, PriceRule, RuleBook
    from pricer.service import LineItem
    
    
    @pytest.fixture
    def book() -> RuleBook[PriceRule]:
        return RuleBook[PriceRule](
            [PercentOff("FIRST50", Decimal(50)), FlatOff("FIVEOFF", Money.of("5.00"))]
        )
    
    
    @pytest.fixture
    def basket() -> list[LineItem]:
        return [
            LineItem("pizza", Money.of("9.50"), 2),
            LineItem("cola", Money.of("2.50"), 1),
        ]
    tests/test_money.py — chunk 5runs offline
    from dataclasses import FrozenInstanceError
    from decimal import Decimal
    
    import pytest
    from hypothesis import given
    from hypothesis import strategies as st
    
    from pricer.money import Money
    
    
    def test_money_is_exact() -> None:
        assert (Money.of("0.10") + Money.of("0.20")) == Money.of("0.30")
    
    
    def test_money_is_immutable_and_hashable() -> None:
        m = Money.of("1.00")
        with pytest.raises(FrozenInstanceError):
            m.amount = Decimal("2.00")  # type: ignore[misc]
        assert {m: "ok"}[Money.of("1.00")] == "ok"
    
    
    def test_currencies_do_not_mix() -> None:
        with pytest.raises(ValueError, match="cannot add"):
            Money.of("1.00", "EUR") + Money.of("1.00", "USD")
    
    
    @given(st.integers(0, 10**6), st.integers(0, 10**6))
    def test_addition_commutes(a: int, b: int) -> None:
        x, y = Money(Decimal(a) / 100), Money(Decimal(b) / 100)
        assert x + y == y + x
    tests/test_rules.py — chunk 5runs offline
    from decimal import Decimal
    
    import pytest
    
    from pricer.money import Money
    from pricer.rules import FlatOff, PercentOff, PriceRule, RuleBook
    
    
    @pytest.mark.parametrize(
        ("rule", "subtotal", "expected"),
        [
            (PercentOff("half", Decimal(50)), "21.50", "10.75"),
            (PercentOff("zero", Decimal(0)), "21.50", "21.50"),
            (FlatOff("five", Money.of("5.00")), "21.50", "16.50"),
            (FlatOff("never negative", Money.of("50.00")), "21.50", "0.00"),
        ],
    )
    def test_rules(rule: PriceRule, subtotal: str, expected: str) -> None:
        assert rule.apply(Money.of(subtotal)) == Money.of(expected)
    
    
    def test_book_find_may_return_none(book: RuleBook[PriceRule]) -> None:
        assert book.find("NOPE") is None
        found = book.find("FIRST50")
        assert found is not None and found.name == "FIRST50"

    conftest.py fixtures, @pytest.mark.parametrize, @given.

    run pytest -q on those two files: nine tests (four money, five rules including the four parametrized rows) pass.

    output · Python 3.12.3runs offline
    .........                                                                [100%]
    9 passed in 0.50s
  6. Chunk 6 — service tests and the patch lesson

    Last, the tests for price_order, including the two patch tests from the idiom: one patches the right name, one patches the wrong name and proves it had no effect.

    Step-by-step: what this chunk does, in plain English
    1. Hand-computed numbers in comments: 21.50 + 19 percent = 25.585, half-even gives 25.58.
    2. patch("pricer.service.fetch_tax_rate") replaces the name where the service looks it up.
    3. patch("pricer.rates.fetch_tax_rate") changes nothing, so the test asserts the price is still taxed.
    4. monkeypatch.setattr does the first job with automatic undo.
    tests/test_service.py — chunk 6runs offline
    from decimal import Decimal
    from unittest.mock import patch
    
    import pytest
    
    from pricer.money import Money
    from pricer.rules import PriceRule, RuleBook
    from pricer.service import LineItem, price_order
    
    
    def test_no_code(basket: list[LineItem], book: RuleBook[PriceRule]) -> None:
        # subtotal 21.50 + 19% tax = 25.585 -> 25.58 (half-even)
        assert price_order(basket, book) == Money.of("25.58")
    
    
    def test_known_code(basket: list[LineItem], book: RuleBook[PriceRule]) -> None:
        # 21.50 * 0.5 = 10.75, * 1.19 = 12.7925 -> 12.79
        assert price_order(basket, book, "FIRST50") == Money.of("12.79")
    
    
    def test_unknown_code_is_ignored(
        basket: list[LineItem], book: RuleBook[PriceRule]
    ) -> None:
        assert price_order(basket, book, "TYPO") == price_order(basket, book)
    
    
    def test_patch_where_it_is_used(
        basket: list[LineItem], book: RuleBook[PriceRule]
    ) -> None:
        with patch("pricer.service.fetch_tax_rate", return_value=Decimal("0.00")):  # ✅
            assert price_order(basket, book) == Money.of("21.50")
    
    
    def test_patch_at_the_source_has_no_effect(
        basket: list[LineItem], book: RuleBook[PriceRule]
    ) -> None:
        with patch("pricer.rates.fetch_tax_rate", return_value=Decimal("0.00")):  # ❌
            assert price_order(basket, book) == Money.of("25.58")  # still taxed!
    
    
    def test_monkeypatch_variant(
        monkeypatch: pytest.MonkeyPatch, basket: list[LineItem], book: RuleBook[PriceRule]
    ) -> None:
        monkeypatch.setattr("pricer.service.fetch_tax_rate", lambda region: Decimal("0.10"))
        assert price_order(basket, book) == Money.of("23.65")

    unittest.mock.patch and monkeypatch with a dotted-name target.

    run pytest -q tests/test_service.py: six tests pass.

    output · Python 3.12.3runs offline
    ......                                                                   [100%]
    6 passed in 0.13s
  7. Chunk 7 — run everything: tests, type checker, linter

    A package is finished when three commands are green. They are the same three that CI would run.

    Step-by-step: what these commands do, in plain English
    1. pytest -q runs all 15 tests. I added -p no:deepeval only because the course venv has an unrelated plugin that prints an extra line.
    2. mypy reads pyproject.toml and checks src and tests in strict mode.
    3. ruff check and ruff format --check lint and verify layout.
    the three green runs · Python 3.12.3runs offline
    $ pytest -q
    ...............                                                          [100%]
    15 passed in 0.22s
    $ mypy
    Success: no issues found in 9 source files
    $ uvx ruff check . && uvx ruff format --check .
    All checks passed!
    9 files already formatted

    Strict mypy: every function in src and tests has full annotations, and the generic RuleBook[PriceRule] is checked.

    All three are green: 15 passed, "Success: no issues found in 9 source files", and "All checks passed!". To see the checker earn its keep, delete the if rule is not None line in service.py and run mypy: it reports Item "None" of "PriceRule | None" has no attribute "apply" (I ran this; it is the same error as Tuesday's crash, found before running).

The whole package

Chunk 1 is pyproject.toml (shown above, 25 lines). The listing below has every Python file, each starting with a # ── chunk n ── marker: money.py is chunk 2, rules.py chunk 3, rates.py and service.py chunk 4, conftest.py and the money and rules tests chunk 5, test_service.py chunk 6. Commands run from the pricer folder.

pricer package · all files · Python 3.12runs offline
# ── chunk 2: money: src/pricer/money.py ──
from dataclasses import dataclass
from decimal import ROUND_HALF_EVEN, Decimal

CENT = Decimal("0.01")


@dataclass(frozen=True, slots=True)
class Money:
    """An amount of one currency. Immutable, hashable, exact."""

    amount: Decimal
    currency: str = "EUR"

    @classmethod
    def of(cls, text: str, currency: str = "EUR") -> "Money":
        return cls(Decimal(text).quantize(CENT, ROUND_HALF_EVEN), currency)

    def __add__(self, other: "Money") -> "Money":
        if self.currency != other.currency:
            raise ValueError(f"cannot add {self.currency} and {other.currency}")
        return Money(self.amount + other.amount, self.currency)

    def times(self, factor: Decimal | int) -> "Money":
        return Money(
            (self.amount * factor).quantize(CENT, ROUND_HALF_EVEN), self.currency
        )

    def __str__(self) -> str:
        return f"{self.amount} {self.currency}"

# ── chunk 3: rules: src/pricer/rules.py ──
from collections.abc import Iterable
from dataclasses import dataclass
from decimal import Decimal
from typing import Protocol

from pricer.money import Money


class PriceRule(Protocol):
    """Anything with a name and an apply() method is a rule. No base class needed."""

    @property
    def name(self) -> str: ...

    def apply(self, subtotal: Money) -> Money:
        """Return the subtotal after the rule."""
        ...


@dataclass(frozen=True, slots=True)
class PercentOff:
    name: str
    percent: Decimal

    def apply(self, subtotal: Money) -> Money:
        return subtotal.times(1 - self.percent / 100)


@dataclass(frozen=True, slots=True)
class FlatOff:
    name: str
    off: Money

    def apply(self, subtotal: Money) -> Money:
        left = subtotal.amount - self.off.amount
        return Money(max(left, Decimal("0.00")), subtotal.currency)


class RuleBook[R: PriceRule]:
    """A lookup of rules by code. find() says honestly that it may find nothing."""

    def __init__(self, rules: Iterable[R]) -> None:
        self._by_name = {r.name: r for r in rules}

    def find(self, name: str) -> R | None:
        return self._by_name.get(name)

    def __len__(self) -> int:
        return len(self._by_name)

# ── chunk 4: rates: src/pricer/rates.py ──
from decimal import Decimal

_RATES = {"DE": Decimal("0.19"), "FR": Decimal("0.20"), "ES": Decimal("0.21")}


def fetch_tax_rate(region: str) -> Decimal:
    """Stands in for an HTTP call to a tax service."""
    return _RATES[region]

# ── chunk 4: service: src/pricer/service.py ──
from collections.abc import Sequence
from dataclasses import dataclass
from decimal import Decimal

from pricer.money import Money
from pricer.rates import fetch_tax_rate
from pricer.rules import PriceRule, RuleBook


@dataclass(frozen=True, slots=True)
class LineItem:
    sku: str
    unit_price: Money
    qty: int


def subtotal(items: Sequence[LineItem]) -> Money:
    total = Money(Decimal("0.00"))
    for item in items:
        total = total + item.unit_price.times(item.qty)
    return total


def price_order(
    items: Sequence[LineItem],
    book: RuleBook[PriceRule],
    code: str | None = None,
    region: str = "DE",
) -> Money:
    """Subtotal, then the discount code (if any and known), then tax."""
    amount = subtotal(items)
    if code is not None:
        rule = book.find(code)
        if rule is not None:  # the checker forces this branch
            amount = rule.apply(amount)
    return amount.times(1 + fetch_tax_rate(region))

# ── chunk 5: fixtures: tests/conftest.py ──
from decimal import Decimal

import pytest

from pricer.money import Money
from pricer.rules import FlatOff, PercentOff, PriceRule, RuleBook
from pricer.service import LineItem


@pytest.fixture
def book() -> RuleBook[PriceRule]:
    return RuleBook[PriceRule](
        [PercentOff("FIRST50", Decimal(50)), FlatOff("FIVEOFF", Money.of("5.00"))]
    )


@pytest.fixture
def basket() -> list[LineItem]:
    return [
        LineItem("pizza", Money.of("9.50"), 2),
        LineItem("cola", Money.of("2.50"), 1),
    ]

# ── chunk 5: tests: tests/test_money.py ──
from dataclasses import FrozenInstanceError
from decimal import Decimal

import pytest
from hypothesis import given
from hypothesis import strategies as st

from pricer.money import Money


def test_money_is_exact() -> None:
    assert (Money.of("0.10") + Money.of("0.20")) == Money.of("0.30")


def test_money_is_immutable_and_hashable() -> None:
    m = Money.of("1.00")
    with pytest.raises(FrozenInstanceError):
        m.amount = Decimal("2.00")  # type: ignore[misc]
    assert {m: "ok"}[Money.of("1.00")] == "ok"


def test_currencies_do_not_mix() -> None:
    with pytest.raises(ValueError, match="cannot add"):
        Money.of("1.00", "EUR") + Money.of("1.00", "USD")


@given(st.integers(0, 10**6), st.integers(0, 10**6))
def test_addition_commutes(a: int, b: int) -> None:
    x, y = Money(Decimal(a) / 100), Money(Decimal(b) / 100)
    assert x + y == y + x

# ── chunk 5: tests: tests/test_rules.py ──
from decimal import Decimal

import pytest

from pricer.money import Money
from pricer.rules import FlatOff, PercentOff, PriceRule, RuleBook


@pytest.mark.parametrize(
    ("rule", "subtotal", "expected"),
    [
        (PercentOff("half", Decimal(50)), "21.50", "10.75"),
        (PercentOff("zero", Decimal(0)), "21.50", "21.50"),
        (FlatOff("five", Money.of("5.00")), "21.50", "16.50"),
        (FlatOff("never negative", Money.of("50.00")), "21.50", "0.00"),
    ],
)
def test_rules(rule: PriceRule, subtotal: str, expected: str) -> None:
    assert rule.apply(Money.of(subtotal)) == Money.of(expected)


def test_book_find_may_return_none(book: RuleBook[PriceRule]) -> None:
    assert book.find("NOPE") is None
    found = book.find("FIRST50")
    assert found is not None and found.name == "FIRST50"

# ── chunk 6: service tests: tests/test_service.py ──
from decimal import Decimal
from unittest.mock import patch

import pytest

from pricer.money import Money
from pricer.rules import PriceRule, RuleBook
from pricer.service import LineItem, price_order


def test_no_code(basket: list[LineItem], book: RuleBook[PriceRule]) -> None:
    # subtotal 21.50 + 19% tax = 25.585 -> 25.58 (half-even)
    assert price_order(basket, book) == Money.of("25.58")


def test_known_code(basket: list[LineItem], book: RuleBook[PriceRule]) -> None:
    # 21.50 * 0.5 = 10.75, * 1.19 = 12.7925 -> 12.79
    assert price_order(basket, book, "FIRST50") == Money.of("12.79")


def test_unknown_code_is_ignored(
    basket: list[LineItem], book: RuleBook[PriceRule]
) -> None:
    assert price_order(basket, book, "TYPO") == price_order(basket, book)


def test_patch_where_it_is_used(
    basket: list[LineItem], book: RuleBook[PriceRule]
) -> None:
    with patch("pricer.service.fetch_tax_rate", return_value=Decimal("0.00")):  # ✅
        assert price_order(basket, book) == Money.of("21.50")


def test_patch_at_the_source_has_no_effect(
    basket: list[LineItem], book: RuleBook[PriceRule]
) -> None:
    with patch("pricer.rates.fetch_tax_rate", return_value=Decimal("0.00")):  # ❌
        assert price_order(basket, book) == Money.of("25.58")  # still taxed!


def test_monkeypatch_variant(
    monkeypatch: pytest.MonkeyPatch, basket: list[LineItem], book: RuleBook[PriceRule]
) -> None:
    monkeypatch.setattr("pricer.service.fetch_tax_rate", lambda region: Decimal("0.10"))
    assert price_order(basket, book) == Money.of("23.65")

Read the result as a map of the section. The frozen dataclass and Decimal come from Section 02. The Protocol and generic class are the typing idioms. find returning RuleBook[...].find -> R | None is Tuesday's incident, closed by the type checker.

The fixtures and the patch test are the testing idioms. And the dependency list is empty on purpose: there is nothing to lock, which is the cheapest lockfile of all. When pricer gains its first real dependency, uv add and uv sync --frozen take over, as shown earlier.

Every number in the tests was worked out by hand first (21.50 plus 19 percent tax is 25.585, which rounds half-to-even to 25.58). That matters more than it looks: a test whose expected value was copied from the program's own output proves nothing.

What to carry out of Sections 06 and 07: choose the concurrency model by what the work waits on, never let a blocking call into the loop, give every task an owner, check types where code meets code and validate data where it meets the world, lock what you deploy, and measure before you optimise.

08 · DrillObjects, Memory & the Data Model — Q1–Q40

The first forty questions cover what a Python senior round always opens with: what a variable really is, how memory is freed, and how len, for, with, + and .attr are wired to special methods. Interviewers use these to separate people who have used Python from people who can explain it. Every answer is written to be said aloud, then proved with code that was actually run on the course machine. Say yours first, then reveal.

Drill · Names, identity and mutability

These questions test whether you hold the "label, not box" model: names point at objects, and most surprises come from two names pointing at one mutable object.

Q1. "What happens in memory when you write a = [1, 2]; b = a; b.append(3)?"

Reveal answer

The real test Whether you say "one list, two labels" or "b is a copy of a".

Strong answer One list object is created. a = [1, 2] builds it and then sticks the name a on it. b = a does not copy anything; it sticks a second name b on the same object.

b.append(3) follows the name b to the object and changes the object itself. Because a points at that same object, a shows [1, 2, 3] too. Nothing happened to a; the thing it points at changed.

A name in Python is a label, not a box. Assignment never copies a value, it only moves a label. That one sentence explains most of the "spooky" bugs in the rest of this chapter.

Java engineers often picture b = a as copying a value into a box called b. That picture is right for Java int and wrong for Python everything. Even 5 is an object; it is just one nobody can change.

Picture it Two labels, one object, then a third label on a real copy.

The setup: Create the list, add a second name, change it through the second name, then make a true copy for contrast.

q01_labels.py · Python 3.14runs offline
import sys

a = [1, 2]
b = a
b.append(3)
print("a:", a, " b:", b)
print("same object:", a is b, " ids equal:", id(a) == id(b))

c = a.copy()
c.append(4)
print("a:", a, " c:", c, " c is a:", c is a)

print("refs to the list (getrefcount adds 1 for its own argument):", sys.getrefcount(a))
b = None
print("after b = None:", sys.getrefcount(a))
output · Python 3.14runs offline
a: [1, 2, 3]  b: [1, 2, 3]
same object: True  ids equal: True
a: [1, 2, 3]  c: [1, 2, 3, 4]  c is a: False
refs to the list (getrefcount adds 1 for its own argument): 3
after b = None: 2

What you see: a and b print the same three items because they are one object. The copy c is a different object, so appending 4 to it leaves a alone.

Why: CPython keeps a counter on every object saying how many labels point at it. Moving b away (b = None) lowers that counter from 3 to 2 (a, plus the temporary reference that getrefcount itself holds). The list lives as long as the counter is above zero.

Land it I say "assignment binds a name to an object and never copies, so b.append changes the one list that both names see."

Likely follow-ups
"So how do I get an independent list?"

Make the copy on purpose, and decide how deep it goes. For a flat list of numbers or strings, b = a.copy(), b = a[:] and b = list(a) all do the same job: they build a new list object and fill it with the same items. After that, b.append(3) changes only b, because the two names point at two different lists.

The catch is the words "the same items". If an item is itself a list, both outer lists point at that one inner list. The run below shows it: the flat copy sees the 99 added through a, and the deep copy does not.

q01_copy.py (output)runs offline
a     [[1, 99], [2]]
flat  [[1, 99], [2]]
deep  [[1], [2]]

So the rule is: ask whether the items are mutable. If not, a shallow copy is enough. If yes, use copy.deepcopy(a). Q7 walks through the nested case, which is where the real production bug lives.

"What does id() return, and can I rely on it?"

There are three facts to hold in your head, and the first one answers the question.

  1. What it is: In CPython, id(x) returns the memory address of the object x points at, as a plain integer. Two names with the same id are labels on one object, which is exactly what is tests.
  2. What it promises: Only that the number is unique among objects alive at the same moment. Once an object is freed, its address can go to a brand-new object, so id values taken at different times can match.
  3. What other Pythons do: On PyPy or Jython the number need not be an address at all. The language promises uniqueness, nothing about meaning.

So I use id for debugging and for demos like Q1, and is for real identity checks. I never store an id as a dict key and expect it to still point at the same thing later; keep the object itself, or a weak reference to it, instead.

"Does the same thing happen with strings and ints?"

Yes, the labelling is identical. You just cannot see it, because those objects cannot be changed. After s = "ab"; t = s, both names point at one string. Then t += "c" builds a new string "abc" and moves the label t onto it. The name s still points at "ab". The same holds for ints, floats and tuples.

The difference appears with += on a list. A list has __iadd__, which extends the list in place and hands back the same object, so b += [4] changes what a sees too. The run shows both cases side by side.

q06_iadd.py (output)runs offline
[1, 2] True      list: += mutated the shared object
x xy False       str: += made a new string
[1] [1, 2]       list: b = b + [2] made a new list

One syntax, two behaviours, decided by whether the type can mutate. Q6 has the extreme version, where the error and the change both happen.

"How does Java compare?"

A Java reference variable behaves exactly like a Python name. List<Integer> b = a; copies the reference, not the list, so b.add(3) shows through a. For objects, the two models agree, and that is why Java engineers usually pick this up quickly.

The difference is the Java primitives. int y = x; copies a raw 4-byte number into a new box, and changing y can never touch x. Python has no primitives. A Python int is a full object with a reference count and a type pointer, about 28 bytes for a small one, and y = x just adds a second label.

This has a cost you can name: a Python list of a million ints holds a million pointers to a million objects, while a Java int[] holds the numbers directly. That is why numeric Python code moves to array or NumPy when memory matters (Q19).

My one-line answer: same model for objects, different for primitives, and Python treats everything as an object.

Q2. "is versus == — and why can x = 257; y = 257; x is y give different answers in the REPL and in a file?"

Reveal answer

The real test Whether you know that is is an implementation detail test and == is the value test, and that you reach for is only with None and sentinels.

Strong answer == asks "do these two objects have equal values?" and calls __eq__. is asks "are these two names pointing at the very same object?" and compares addresses. It cannot be overridden.

CPython keeps a pre-built cache of the integers -5 to 256. Every time the program needs the number 100, it gets the same cached object, so 100 is 100 is True. That is a speed trick, not a language promise.

257 is outside the cache. Whether two 257s are one object depends on how the code was compiled. In a REPL each line is compiled separately, so each line makes its own 257 object and is says False. Inside one function or file, the compiler sees both 257 constants together and stores one shared object in the code's constants, so is says True.

The rule that follows: use == for values, and is only for None, True, False and your own sentinel objects.

Picture it The same two assignments, run three ways, on the course machine.

The setup: One script that compiles x = 257; y = 257 as separate units, as one unit, and builds the number at runtime.

q02_is_trap.py · Python 3.14runs offline
# way 1: each statement compiled on its own, like typing in a REPL
ns = {}
exec("x = 257", ns)
exec("y = 257", ns)
print("separate compile units :", ns["x"] is ns["y"])

# way 2: both constants in one compile unit
ns2 = {}
exec("x = 257\ny = 257", ns2)
print("one compile unit       :", ns2["x"] is ns2["y"])

# way 3: values created at runtime
a, b = int("257"), int("257")
print("int('257') twice       :", a is b, " equal:", a == b)

# the cache edge: -5..256
for n in (-6, -5, 256, 257):
    p, q = int(str(n)), int(str(n))
    print(f"int(str({n})) twice: is -> {p is q}")
output · Python 3.14runs offline
separate compile units : False
one compile unit       : True
int('257') twice       : False  equal: True
int(str(-6)) twice: is -> False
int(str(-5)) twice: is -> True
int(str(256)) twice: is -> True
int(str(257)) twice: is -> False

What you see: separate units give False, one unit gives True (the compiler folded the two constants into one), and runtime-built numbers give False. The edges show the cache: -5 and 256 are shared, -6 and 257 are not.

Why: Nothing in the language says which answer you get. A different Python version, or a different implementation such as PyPy, may print something else. Code that depends on the answer is wrong by definition.

Land it I use == for value comparison and is only for None and sentinels, because identity of numbers is a CPython cache detail.

Likely follow-ups
"Why does Python warn about x is 257?"

It is a deliberate nudge. Since Python 3.8 the compiler prints SyntaxWarning: "is" with 'int' literal. Did you mean "=="? when it sees x is 257 or x is "abc". It appears at compile time, before the program runs.

The reason is that this bug hides well. x is 5 works in every test, because the small-int cache (-5 to 256) hands out one shared object. In production a value of 5000 arrives, the two sides are different objects, and the branch silently goes the wrong way. The result depends on how the number was created, so it can even pass on one machine and fail on another.

What I do in practice: run tests with -W error::SyntaxWarning in CI, or enable the Ruff rule that flags identity comparison with a literal (F632). The check costs nothing and removes a whole class of bug. The only literals that deserve is are None, True and False.

"Why is x is None right when x == None also works?"

Two reasons, one about correctness and one about speed.

  1. Nobody can fool it: A class may define __eq__ so that it claims to equal None. Some array libraries return a whole array of True/False from arr == None, which then breaks an if. x is None compares addresses, and there is exactly one None object in the process, so no class can change the answer.
  2. It is cheaper: is compares two pointers in one step and never calls a method. == has to find and run __eq__. The saving is small per call, but it costs nothing to take.
  3. It is the style rule: PEP 8 says comparisons to singletons such as None should use is or is not, and linters flag == None.

So x == None usually works, and I still never write it. The one time it fails is a data-science library, which is exactly where you will be reading the bug report.

"When do two equal objects not have the same identity?"

Almost always, for anything that is not cached. [1] == [1] is True because the contents match, and [1] is [1] is False because each list display builds a new object. Equal but not identical is the normal state of the world.

The direction matters. Same identity implies equal, for any sane class, because an object equals itself. The reverse does not hold. NaN is the odd one out, and the run shows it.

q02_nan.py (output)runs offline
True False     nan is nan, nan == nan
True False     [nan] == [nan] (same object), then two different nans
True False     [1] == [1], then [1] is [1]

Lists compare items by identity first and equality second, so [nan] == [nan] is true when it is the very same nan object, but not for two separately made ones. That is why x == x is not a safe test for "x is a normal value", and why float keys in dicts deserve suspicion.

"Can I make is return True for equal strings?"

Yes, with sys.intern(s). It returns the one shared copy of a string that has the same characters, so any two strings you pass through it are the same object and is says True. Here is the run, using strings built at runtime so the compiler did not share them.

q08_size.py (output, last two lines)runs offline
[True, False, False]    three built strings: only the first matches itself
[True, True, True]      the same three after sys.intern

The first list is a check of each string against the first, so the leading True is trivial. Without interning, the other two are separate objects. After interning, all three are one object.

Q8 covers when that is worth doing, which is mostly memory for millions of repeated labels. For ordinary comparison code I would stop wanting it, because == gives the same answer on equal strings and does not depend on how they were made. The interning table is an implementation detail, so a test that relies on is is a test that breaks on the next Python version.

Q3 · Scenario. "A function def add(item, bucket=[]) returns items from earlier calls in production. Explain exactly why, and fix it."

Reveal answer

Strong answer A default value is evaluated once, when the def statement runs, not each time the function is called. The list [] is created at that moment and stored on the function object in add.__defaults__.

Every call that omits bucket receives that same stored list. The first caller appends "FIRST50" to it; the second caller's "empty" bucket already contains it. The function is not broken; the default is shared state that looks like a fresh value.

The fix is the None sentinel: default to None, and build a new list inside the body when you see None. Now the list is created per call.

If None is itself a valid argument, use a private sentinel object such as _MISSING = object() and compare with is. See the None-default idiom.

Picture it The default list growing between calls, then the fix.

The setup: A pricer helper that collects discount codes, written the wrong way first.

q03_mutable_default.py · Python 3.14runs offline
def add_bad(item, bucket=[]):          # ❌ TRAP: one list for every call
    bucket.append(item)
    return bucket

print(add_bad("FIRST50"))
print(add_bad("VIP10"))                # customer B sees customer A's code
print("stored defaults:", add_bad.__defaults__)

def add_good(item, bucket=None):       # ✅ None sentinel
    if bucket is None:
        bucket = []
    bucket.append(item)
    return bucket

print(add_good("FIRST50"))
print(add_good("VIP10"))
print("stored defaults:", add_good.__defaults__)
output · Python 3.14runs offline
['FIRST50']
['FIRST50', 'VIP10']
stored defaults: (['FIRST50', 'VIP10'],)
['FIRST50']
['VIP10']
stored defaults: (None,)

What you see: the second add_bad call returns both codes, and __defaults__ shows the list that kept growing inside the function object. The fixed version stores only None, so every call starts clean.

Why: def is an executable statement. Its default expressions run once, and the results sit on the function until it is deleted.

Naive Python

Looks fresh, is shared.

add_bad.pyruns offline
def add(item, bucket=[]):
    bucket.append(item)
    return bucket

Python idiom

None means "make a new one".

add_good.pyruns offline
def add(item, bucket=None):
    if bucket is None:
        bucket = []
    bucket.append(item)
    return bucket

The shift: A default is a value stored once on the function, so a mutable default is hidden global state.

Land it I explain that defaults are evaluated once at def time and stored in __defaults__, and I fix it with a None sentinel that builds the list inside the call.

Likely follow-ups
"Is a mutable default ever useful on purpose?"

Yes, as a deliberate cache. def fib(n, memo={}) stores results in the dict that lives in fib.__defaults__, so the second call reuses the first call's work. It is legal, it works, and it is a classic trick.

The trouble is communication. The next reader sees a mutable default and cannot tell whether it is a bug or a feature. Tests that expect each call to start fresh now depend on call order, because the first test warms the cache for the second. And you cannot clear it without reaching into __defaults__.

I would rather write @functools.cache, which is bounded or clearable (fib.cache_clear()) and says what it is. If I need a shared dict that I control, a module-level _MEMO = {} with a name that explains itself is clearer than a hidden default. If a reviewer asks me to keep the default trick, I ask for a comment saying that the sharing is intended.

"What if None is a legal value for the argument?"

Then None cannot also mean "the caller gave me nothing", so you need a marker nobody else can produce.

  1. Create the marker once: At module level write _MISSING = object(). A bare object() is a new, featureless object that equals nothing but itself.
  2. Default to it: def add(item, bucket=_MISSING):. The default is evaluated once, which is fine here, because the marker is never mutated.
  3. Test with is: Inside, write if bucket is _MISSING: bucket = []. A caller who passes None now gets None through, as intended.

Nobody outside the module holds a reference to _MISSING, so no caller can pass it by accident. Python 3.15 adds a standard sentinel helper (PEP 661); I would check the 3.15 What's New before relying on it, and keep the object() idiom for code that must run on 3.12 and 3.14.

"Do linters catch this?"

Yes. Ruff has rule B006 (mutable argument default) and pylint has W0102 (dangerous-default-value). Both flag [], {} and set() as defaults. Turn them on in CI. The bug is silent at runtime, and the lint rule is free.

Remember that the problem is wider than empty containers. Any expression in a default is evaluated once, when def runs. def f(now=datetime.now()) freezes the import time into every call. def f(conn=connect()) opens one connection at import and shares it for the life of the process, including across threads.

Linters catch the obvious literal cases and miss the call cases, so I also read defaults in review. My question for every default is: would it still be right if this function were called a million times in one process? If the answer is no, the default should be None plus a line inside the body.

"Why did the bug only show up in production?"

Because tests and production run in different shapes. A test usually calls the function once or twice, or starts a fresh process per test file, so the shared list begins empty and looks correct. A long-running server calls the function millions of times in one process, and every call that omits bucket appends to the same list.

That is also why the symptom looked strange. Customer B did not get a random value; B got A's "FIRST50", because both calls received the one list sitting in add.__defaults__. The list also never shrinks, so memory creeps up with traffic, and a restart "fixes" it until the next day.

The test that would have caught it is cheap: call the function twice in a row without a second argument and assert that the second result does not contain the first call's item. For any function with a container default I add that two-call test, because it is the same shape as the production load, just smaller.

Q4. "Is Python pass-by-value or pass-by-reference?"

Reveal answer

The real test Whether you can name "pass by object reference" (call by sharing) and show both a mutation and a rebinding.

Strong answer Neither, exactly. Python passes a reference to the object, by value. People call it "call by sharing" or "pass by object reference". The parameter name inside the function is a new label stuck on the same object the caller passed.

So two things can happen. If the function mutates the object (xs.append(1)), the caller sees the change, because it is one object. If the function rebinds the parameter (xs = [1]), only the local label moves, and the caller's variable still points at the old object.

A true pass-by-reference language would let the function change the caller's variable itself. Python never can; the only way to change the caller's name is to return a value and have the caller rebind it.

Java is the same model for objects: references are passed by value. The difference is only that Java has primitives, which are copied.

Picture it One function that mutates, one that rebinds, and an id printed at each step.

The setup: Pass a list into two functions and watch what the caller sees.

q04_call_by_sharing.py · Python 3.14runs offline
def mutate(xs):
    print("  inside mutate, id:", id(xs))
    xs.append(1)

def rebind(xs):
    xs = [99]                      # moves the local label only
    print("  inside rebind, id:", id(xs))

data = []
print("caller id:", id(data))
mutate(data)
print("after mutate:", data)
rebind(data)
print("after rebind:", data)
output · Python 3.14runs offline
caller id: 136625184087936
  inside mutate, id: 136625184087936
after mutate: [1]
  inside rebind, id: 136625174216320
after rebind: [1]

What you see: mutate prints the caller's id and the change appears in data. rebind prints a different id (the new list), and data is unchanged.

Why: Parameters are local names bound to the argument objects. Mutation reaches the shared object; rebinding only moves the local label.

Java · Spring

Reference passed by value.

Calls.javaruns offline
void mutate(List<Integer> xs) {
  xs.add(1);          // caller sees it
}
void rebind(List<Integer> xs) {
  xs = new ArrayList<>(); // caller does not
}

Python

Same model, no primitives.

calls.pyruns offline
def mutate(xs):
    xs.append(1)      # caller sees it

def rebind(xs):
    xs = []           # caller does not

The shift: Both languages share the reference; Java copies primitives, Python has none, so "everything is an object reference".

Land it I say Python passes object references by value, so mutation is visible to the caller and rebinding is not.

Likely follow-ups
"How do I protect a caller's list from my function?"

Do not change the argument unless the function's name says you will. Build and return a new list: return [*xs, 1] to add an item, or sorted(xs) to order it. The caller's list is untouched, and the caller decides whether to rebind.

If the work really is easier in place, copy at the top: xs = list(xs). This is one new list with the same items, which is enough when the items are numbers or strings. For nested data, copy.deepcopy is the safer choice (Q7).

A naming convention helps readers. Methods such as sort, append and extend mutate and return None. Functions such as sorted return a new object. If your function mutates, say so in the name (normalise_in_place) and in the docstring.

In review I ask, for each list or dict parameter, "does this function change it?" If yes and it is not obvious, I want it renamed or copied.

"Why does list.sort() return None?"

It is a deliberate signal, and it is easy to see once you picture the bug it prevents.

  1. The rule: A method that changes the object in place returns None. That way you cannot write y = xs.sort() and believe that y is a new sorted list while xs changed under you.
  2. The classic mistake: xs = xs.sort() sorts the list and then rebinds xs to the return value, which is None. The next line fails with 'NoneType' object is not iterable.
  3. The fix: Use xs.sort() on its own line when you want in-place, or xs = sorted(xs) when you want a new list. The second also works on any iterable, such as a set or a generator.

The same convention covers list.reverse, list.append, dict.update and set.add. Python borrowed it from the idea of command-query separation: a call either changes something or answers a question, not both.

"Can a function change an immutable argument, like a string?"

No object-level change is possible, so a function cannot change an immutable argument. Inside the function, s += "x" builds a new string and rebinds only the local name s. The caller's string is untouched. The same goes for ints, floats, tuples and frozensets.

That has a practical consequence. If a function should hand back a modified number or string, it must return it, and the caller must rebind: n = bump(n). There is no way to write a swap(a, b) function that works on two ints, because the function only ever sees its own labels.

A tuple adds one subtlety. The tuple itself cannot change, but if one of its items is a list, a function can still mutate that list (Q6). Immutability is about which objects the container points at, not about what those objects contain.

So the rule I teach is: immutable argument, return the new value. Mutable argument, decide on purpose whether to change it.

"What about default values and class attributes, where mutation hides?"

The same rule applies, and that is the useful part. A mutable default argument (Q3) is one object shared by every call that omits the argument. A mutable class attribute, class A: items = [], is one object shared by every instance, because instances look it up through the class unless they set their own.

Here is the trace. a1 = A(); a2 = A(); a1.items.append(1) follows the name items from a1 to the class, finds the one list, and changes it. Now a2.items shows [1]. Compare a1.items = [], which rebinds on the instance and creates an instance attribute that hides the class one.

The question I ask of any [] or {} I meet is: who else holds a reference to this exact object? For defaults and class attributes the answer is "everyone", and the fix is the same each time: create the container inside __init__ or the function body, or use field(default_factory=list) in a dataclass, which refuses a bare list default.

Q5. "Which built-in types are mutable and which are immutable, and why does that decide what can be a dict key?"

Reveal answer

Strong answer Immutable: int, float, bool, complex, str, bytes, tuple, frozenset, range, None, and in 3.15 frozendict. Mutable: list, dict, set, bytearray, and almost every class instance you write.

A dict finds a key by its hash, a number computed from the key's value. The dict stores the key in the slot that hash points at. If the key could change, its hash would change, and the dict would look in the wrong slot and lose the entry.

So Python only lets you use objects whose hash is stable: the rule is "hashable means immutable by value". A list as a key raises TypeError ("unhashable type: 'list'").

Immutable does not mean "deep". A tuple holding a list is a tuple, but hashing it hashes the list and fails. Hashability is checked from the outside in, all the way down.

Picture it Which keys work and which are refused.

The setup: Try a tuple of numbers, a tuple containing a list, a list, a frozenset and a dict as keys.

q05_hashable.py · Python 3.14runs offline
good = {(1, 2): "tuple", frozenset({1, 2}): "frozenset", "ab": "str"}
print("good keys:", list(good))

for label, key in [("list", [1, 2]), ("tuple holding a list", ([1], 2)),
                   ("dict", {"a": 1}), ("set", {1})]:
    try:
        {key: 1}
    except TypeError as e:
        print(f"{label:22} -> TypeError: {e}")

print("hash of equal tuples:", hash((1, 2)) == hash((1, 2)))
output · Python 3.14runs offline
good keys: [(1, 2), frozenset({1, 2}), 'ab']
list                   -> TypeError: cannot use 'list' as a dict key (unhashable type: 'list')
tuple holding a list   -> TypeError: cannot use 'tuple' as a dict key (unhashable type: 'list')
dict                   -> TypeError: cannot use 'dict' as a dict key (unhashable type: 'dict')
set                    -> TypeError: cannot use 'set' as a dict key (unhashable type: 'set')
hash of equal tuples: True

What you see: the first three work. The list, the tuple that holds a list, the dict and the set all fail with unhashable type.

Why: hash() of a tuple combines the hashes of its items. A list has no hash, so the tuple has none either.

Land it I say hashable means "value cannot change and equal objects hash equally", which is why lists and dicts cannot be keys and tuples of immutables can.

Likely follow-ups
"Why is hash(1) == hash(1.0) and does it matter?"

It follows from one rule: if a == b, then hash(a) must equal hash(b). Since 1 == 1.0 is True, both hash to 1, and a dict treats them as one key. The run shows it, including the surprise that the first key's spelling stays while the value is replaced.

q05_hash.py (output)runs offline
1 1 1
{1: 'b'} 1

The first line includes hash(True), because True == 1 too. Setting d[1.0] = "b" did not add a second key. It overwrote the value under the key 1.

It matters for data from JSON or CSV, where the same id may arrive as 1 in one record and 1.0 in another (spreadsheets love to do this). That is harmless for a dict, and surprising for code that expects two groups. I normalise number types at the boundary before using them as keys.

"Can I put my own class instance in a dict key?"

Yes, and the default behaviour is identity hashing. A plain class takes its hash from the object's address, so two instances that look alike are two different keys. That is often what you want for entities such as a connection or a session.

If you define __eq__, Python sets __hash__ to None for that class, and instances stop being usable as keys until you define a matching __hash__ (Q22). The matching rule is that equal objects must hash equally, so hash exactly the fields that __eq__ compares, and only fields that cannot change while the object sits in a dict.

For value-like keys such as a price rule, a coordinate or a currency pair, the right shape is a frozen dataclass: @dataclass(frozen=True) writes __eq__ and __hash__ from the same fields and stops anyone from changing them. For mutable entities, I key the dict by a stable id field, not by the object.

"Is frozenset the same as a set that never changes?"

Yes in behaviour, with one extra ability, and one cost to know about.

  1. The ability: A frozenset is hashable, so it can be a dict key or a member of another set. Example: a set of permission sets, {frozenset({"read", "write"})}, or a dict from frozenset({"A", "B"}) to a route, where order must not matter.
  2. What stays the same: Lookup, union, intersection and difference work as for a set. Membership tests are O(1) on average, and the memory layout is the same.
  3. The cost: You cannot add or remove items. To change one, build a new frozenset, for example fs | {"admin"}, which copies the items.

So I use frozenset when the set is a value (a key, a constant, a field of a frozen dataclass), and a plain set when I am building or updating it. In short, it is a set that promised not to move.

"If tuples are immutable, why can a tuple's contents change?"

Because "immutable" means the tuple's slots cannot be reassigned, not that the objects in the slots are frozen. Each slot holds a reference, and a tuple promises only that slot 0 will always point at the same object. If that object is a list, the list can still change.

Take t = ([1], 2). The line t[0].append(9) works, because it never assigns into the tuple; it follows the reference and mutates the list. The line t[0] = [9] raises TypeError, because it tries to rebind slot 0.

The consequence for hashing is direct. hash(t) hashes every item, so a tuple holding a list fails with unhashable type: 'list'. A tuple is hashable only if everything in it is, all the way down. Q6 shows an operation that does both at once, the error and the change.

My practical rule: if I want a value that cannot change at any depth, I build it from numbers, strings, tuples and frozensets, and nothing else.

Q6 · Scenario. "t = ([1], 2); t[0] += [3] raises TypeError — yet t has changed afterwards. Explain step by step."

Reveal answer

The real test Whether you know that augmented assignment is "get, in-place add, store back", and that the store is the step that fails.

Strong answer t[0] += [3] is not one operation. Python runs it as three: fetch t[0], add in place, then store the result back into t[0].

Step 1 fetches the inner list. Step 2 calls the list's __iadd__, which extends that same list and returns it. The list now holds [1, 3]. That step succeeded, and it changed an object the tuple points at.

Step 3 stores the returned list back into slot 0 of the tuple with t[0] = .... A tuple refuses item assignment, so Python raises TypeError. The error is real, but the damage from step 2 is already done and is not rolled back.

The lesson has two halves. Tuples are immutable only in which objects they point at, not in what those objects contain. And += on a list mutates, which is why the error and the change both happen.

Picture it The statement, then the same work as three visible steps, then the bytecode that proves the order.

The setup: Run the one-liner, then replay it by hand.

q06_tuple_iadd.py · Python 3.14runs offline
import dis

t = ([1], 2)
try:
    t[0] += [3]
except TypeError as e:
    print("TypeError:", e)
print("t is now:", t)

print("--- same thing in three steps")
t = ([1], 2)
inner = t[0]                    # step 1: fetch the list
inner = inner.__iadd__([3])     # step 2: mutates in place, returns SAME list
print("after step 2, t is:", t)
try:
    t[0] = inner                # step 3: store back, tuple refuses
except TypeError as e:
    print("step 3:", e)

print("--- bytecode of the statement")
dis.dis(compile("t[0] += [3]", "<stmt>", "exec"))
output · Python 3.14runs offline
TypeError: 'tuple' object does not support item assignment
t is now: ([1, 3], 2)
--- same thing in three steps
after step 2, t is: ([1, 3], 2)
step 3: 'tuple' object does not support item assignment
--- bytecode of the statement
  0           RESUME                   0

  1           LOAD_NAME                0 (t)
              LOAD_SMALL_INT           0
              COPY                     2
              COPY                     2
              BINARY_OP               26 ([])
              LOAD_SMALL_INT           3
              BUILD_LIST               1
              BINARY_OP               13 (+=)
              SWAP                     3
              SWAP                     2
              STORE_SUBSCR
              LOAD_CONST               1 (None)
              RETURN_VALUE

What you see: the one-liner raises and t is already ([1, 3], 2). The replay shows the change landing at step 2, before the store fails at step 3. The dis listing has BINARY_OP (+=) followed by STORE_SUBSCR, the fetch, the in-place add, and the store.

Why: STORE_SUBSCR is the step that calls the tuple's missing __setitem__. Everything before it has already happened.

Land it I explain that += is fetch, in-place add, store back, so the list mutates in step two and the tuple rejects the store in step three.

Likely follow-ups
"How do I extend that inner list without the error?"

Skip the store. t[0].extend([3]) and t[0].append(3) are plain method calls: Python fetches the list out of slot 0 and changes it. Nothing is written back into the tuple, so no TypeError can happen.

The reason this works where += fails is the number of steps. t[0] += [3] is fetch, in-place add, then store into t[0], and the third step is the one a tuple refuses. A method call has only the first two steps.

The cleaner fix is not to hide a mutable list inside something you treat as a value. If the data should not change, use a tuple of tuples, (1,) instead of [1], or a frozen dataclass whose fields are tuples. If the data should change, keep it in a list or an object that is honestly mutable, and do not wrap it in a tuple just to pass it around. A value that is half frozen is harder to reason about than either extreme.

"Why does += on a list change it in place but += on a string does not?"

Python tries __iadd__ first, and falls back to __add__ plus rebinding. The statement a += b means: if type(a) has __iadd__, set a = a.__iadd__(b); otherwise set a = a + b.

A list defines __iadd__. It extends itself and returns self, so the "rebinding" lands on the same object. A string has no __iadd__, so s += "x" becomes s = s + "x", which builds a new string and moves the label.

This is why a += b and a = a + b are not the same for lists. The first changes the one list every name sees. The second builds a new list and moves only the name a. Two names for one list, x = y = [], make the difference visible: x += [1] changes y, and x = x + [1] does not.

It also explains Q6. A tuple slot can hold the list, the list can be extended, and only the final store is refused.

"Is the half-done state a bug in Python?"

No, it is the documented behaviour, and the reason is worth saying in three short points.

  1. Each step is atomic by itself: Fetching an item, calling __iadd__ and storing a result each finish or fail as a unit. The language does not wrap a whole statement in a transaction.
  2. No rollback exists: When step three raises, Python does not undo step two. Undoing arbitrary Python code would need every object to support it, and none do. The same is true of a half-finished loop or a half-written file.
  3. The tools are immutability: The cure is to make the change impossible rather than reversible: tuple, frozenset, frozen dataclasses and, in 3.15, frozendict.

Databases give you transactions. Plain Python objects do not, so for a multi-step change I either build the new value first and swap it in with one assignment, or I keep the data immutable and never need to roll back.

"Does the same thing happen with dictionaries?"

Yes, the same three steps appear. With d = {"k": [1]}, the line d["k"] += [2] is: fetch d["k"], call __iadd__ on the list, then call d.__setitem__("k", result). On a normal dict the store succeeds and stores the same list back, so everything looks harmless.

Make the store step fail and you recreate the tuple case. A read-only MappingProxyType refuses __setitem__, yet the list inside was already extended. The run shows it.

q06_dict_proxy.py (output)runs offline
TypeError: 'mappingproxy' object does not support item assignment
{'k': [1, 2]}

The error is real, and the underlying dict now holds [1, 2]. A read-only view stops you rebinding keys; it does not freeze the values. For safe mutation I call d["k"].append(2) on purpose, or I freeze the values too.

Q7 · Scenario. "A shallow .copy() of a nested config let one tenant's change leak into every tenant. Explain shallow versus deep copy and fix it."

Reveal answer

Strong answer A shallow copy builds one new outer container and fills it with the same inner objects. A deep copy (copy.deepcopy) walks the whole structure and builds new inner objects too.

The pricer config was {"tax": {...}, "fees": [...]}. base.copy() made a new outer dict, but its "fees" key pointed at the very same list. When tenant A appended a fee, it landed in the shared list, and every tenant built from base charged the new fee.

The fix is to copy at the boundary: copy.deepcopy(base) when you hand each tenant its config. A second, stronger fix is to make the config immutable so nobody can edit it at all, for example a frozen dataclass whose fees are a tuple.

Deep copy is not free. It is slow for big structures, and it follows objects that should not be copied, such as open connections. Copy plain data; share services.

Picture it The leak, the fix and what "shared" means in object terms.

The setup: One base config, two tenants, one edit.

q07_shallow_deep.py · Python 3.14runs offline
import copy

def make_base():
    return {"tax": {"rate": "0.08"}, "fees": ["delivery"]}

base = make_base()
a = base.copy()                           # ❌ TRAP: shallow
b = base.copy()
a["fees"].append("surge")
print("base fees   :", base["fees"])
print("tenant B    :", b["fees"])
print("same list?  :", a["fees"] is base["fees"], "| same outer dict?", a is base)

base = make_base()
a = copy.deepcopy(base)                   # ✅ independent inner objects
b = copy.deepcopy(base)
a["fees"].append("surge")
print("after deepcopy -> base:", base["fees"], " B:", b["fees"], " A:", a["fees"])
output · Python 3.14runs offline
base fees   : ['delivery', 'surge']
tenant B    : ['delivery', 'surge']
same list?  : True | same outer dict? False
after deepcopy -> base: ['delivery']  B: ['delivery']  A: ['delivery', 'surge']

What you see: with the shallow copy every config shows ["delivery", "surge"], and the is checks print True for the shared list and False for the outer dict. With deep copies only tenant A has the surge fee.

Why: copy() copies one level. Whatever the first level points at stays shared.

Shallow

One new box, same contents.

shallow.pyruns offline
b = base.copy()
a = base.copy()
a["fees"].append("x")
# base, a, b all changed

Deep or frozen

New contents, or no edits.

deep.pyruns offline
a = copy.deepcopy(base)
b = copy.deepcopy(base)
a["fees"].append("x")
# only a changed

The shift: Decide who owns each inner object: copy it, or make it unchangeable so sharing is safe. See the copy idiom.

Land it I name the level that is shared, copy deliberately at the boundary with deepcopy or freeze the config, and I add a test that edits one tenant and checks another.

Likely follow-ups
"Which copy methods are shallow?"

These are all shallow: dict.copy(), list.copy(), xs[:], list(xs), dict(d), a dict display that unpacks another dict, set(s) and copy.copy(x). Each one creates a single new outer container and reuses the items inside it. If an item is a list or a dict, both containers now point at it.

copy.deepcopy is the only standard one-call way to copy every level. It is a recursive walk that keeps a memo table of what it has already copied. That makes it safe, and also slow and memory-hungry: copying a 100 MB structure roughly doubles memory while both exist.

So I treat deepcopy as something to do once, at a boundary, for small plain data such as a config. It also follows objects you do not want to copy, such as open connections.

My review habit: any .copy() on an object with a nested list, dict or set gets one question, "who owns the inner ones?"

"How does deepcopy avoid infinite loops on cycles?"

It keeps a memo dictionary that maps id(original) to the copy it already made. Before copying an object it looks in the memo. If the object is there, it reuses that copy instead of recursing, which stops infinite loops on cycles. If not, it makes the copy, records it, and then copies the contents.

A useful side effect is that sharing inside the structure is preserved. Two references to one list in the original become two references to one new list in the copy. The run below builds both a shared list and a cycle.

q07_memo.py (output)runs offline
True False True

The three values mean: c["a"] is c["b"] (sharing kept), c["a"] is shared (the copy is new, not the original), and c["self"] is c (the cycle points at the copy, not the original). Without the memo this input would recurse until it hit the recursion limit.

"What is the cheaper option if configs are big?"

Make the config immutable and share it, so that nobody can change it and there is nothing to copy.

  1. Freeze the shape: A frozen dataclass whose fields are tuples, or MappingProxyType over the top-level dict with tuples below. Any attempt to edit raises an error at the line that tried.
  2. Share one object: Every tenant holds a reference to the same base config. No copy is made, so there is no memory cost per tenant.
  3. Build changes as new objects: When one tenant needs an extra fee, call dataclasses.replace(cfg, fees=cfg.fees + ("surge",)). Only the changed field is new, and the other fields are shared.

The run below shows the base staying untouched while the tenant gets the new fee.

q07_replace.py (output)runs offline
('service',) ('service', 'surge')
"How would you test for this bug?"

I build two objects from the same base, change one through every public path, and assert that the other still equals a fresh copy of the base. On a shallow copy, that test fails immediately, and the failure message names the leaked field.

The test is small and does not depend on knowing where the bug is. It looks like this in words: make a and b from base; call each mutating method on a (add a fee, change a tax rate); then assert that b equals fresh_from_base(). A second line asserts a equals what was expected, so the test also catches a copy that is too deep and loses the change.

In code review I also search for .copy() on any object with a nested list, dict or set field, and ask who owns the inner ones. If the answer is "nobody", the fix is either a deep copy at the boundary or making the structure immutable. The leak only needs one such line to reach every tenant.

Q8. "What is string interning, and when (if ever) should your code rely on it?"

Reveal answer

Strong answer Interning means keeping one shared copy of equal strings so they can be compared by address. CPython does it automatically for identifier-like string constants (letters, digits and underscores) and for names of variables and attributes. You can ask for it with sys.intern(s).

The point is speed for names. Attribute lookup compares dict keys, and when both keys are the same object the comparison is one pointer check rather than a character-by-character match.

Your code should almost never rely on it for correctness. Whether a given string is interned depends on how it was created and on the Python version, so s is t for strings is unreliable. Compare strings with ==.

The honest use for sys.intern is a memory and speed optimisation when you hold millions of repeating strings, such as a status column with ten distinct values, and compare them often.

Picture it Strings that are interned automatically, strings that are not, and sys.intern fixing it.

The setup: Compile the same literal in separate units, then build equal strings at runtime.

q08_intern.py · Python 3.14runs offline
import sys

ns = {}
exec("a = 'hello'", ns); exec("b = 'hello'", ns)
print("identifier-like literal, two units :", ns["a"] is ns["b"])

exec("a = 'hello world!'", ns); exec("b = 'hello world!'", ns)
print("literal with space and '!'         :", ns["a"] is ns["b"])

s1 = "".join(["hello", " world!"])
s2 = "".join(["hello", " world!"])
print("built at runtime, equal            :", s1 == s2, " identical:", s1 is s2)
print("after sys.intern                   :", sys.intern(s1) is sys.intern(s2))
output · Python 3.14runs offline
identifier-like literal, two units : True
literal with space and '!'         : False
built at runtime, equal            : True  identical: False
after sys.intern                   : True

What you see: the identifier-like literal is shared across units, the one with a space is not, and two runtime-built equal strings are different objects until sys.intern makes them one.

Why: automatic interning applies to a narrow set of strings. Runtime-built strings are never interned unless you ask.

Land it I never rely on interning for correctness; I use ==, and I reach for sys.intern only to save memory on millions of repeated labels.

Likely follow-ups
"How much memory can interning save?"

Take a worked example, and measure the one number it hangs on.

  1. Size of one string: On my 3.12 build, sys.getsizeof("active") is 47 bytes, so a 7-character ASCII string is about 48: a 41-byte header plus one byte per character.
  2. Without interning: 5 million rows, each with its own status string read from a CSV, hold 5 million separate objects. 5,000,000 x 48 is about 240 MB, plus 8 bytes per row for the pointer.
  3. With interning: Ten distinct statuses become ten objects. The 240 MB of string objects drops to a few hundred bytes. You still pay the 8-byte pointer per row, which is 40 MB.

You pay one dict lookup per row at load time, which is cheap. The saving is real, about 240 MB here, and the figure scales with row count and string length. For labels with a fixed set of values, an enum or pandas.Categorical is usually cleaner, because it also stores each row as a small integer code.

"Does Python free interned strings?"

Whether an interned string can be freed once nothing else uses it has changed between CPython versions, so I do not build anything that depends on the answer. Strings you intern with sys.intern live in an internal table, and different releases have treated that table differently: sometimes the entries are released when the last outside reference goes, sometimes they live for the whole process. Check the sys.intern documentation and What's New for the exact version you run.

What I do depend on is the safe part of the contract: sys.intern(s) returns a string equal to s, and two calls with equal strings return the same object.

The practical rule follows from the uncertainty. Intern only values from a small, fixed vocabulary, such as statuses, country codes and column names. Never intern unbounded input such as user ids, URLs or free text. If the table keeps entries alive, that would turn into a slow leak. When it matters, measure resident memory with tracemalloc before and after, on the interpreter you ship.

"Why do Java engineers recognise this?"

It is the same idea as Java's string pool and String.intern(). Java guarantees that string literals are pooled, so "a" == "a" is true there, and new String("a") == "a" is false. Every Java engineer has been told not to compare strings with ==, and for the same reason: pooling is not promised for strings created at runtime.

Python has exactly the same trap. CPython interns identifier-like constants automatically, so "abc" is "abc" often prints True in a file. A string built at runtime, such as "".join(["a", "bc"]), is a new object and is says False.

The practical rule is identical in both languages: .equals() in Java, == in Python, for every value comparison. The interviewer is checking whether you know that the speed trick is not a correctness tool. A small difference is that Python makes the intern table cheaper to reach, because attribute and variable names are interned by the compiler for you.

"Are there other interned or cached objects?"

Yes, and the list is a good test of whether you know it is an implementation detail. CPython shares the small ints from -5 to 256 (Q2), the empty tuple, None, True, False and Ellipsis, plus many single-character strings, and it interns identifier-like string constants. Since 3.12, several of these are also immortal, so their reference counts are never changed.

None of this is part of the language. PyPy and other implementations make different choices, and CPython changes details between releases. A program whose answer depends on is for numbers or strings is a program with a latent bug.

The follow-up an interviewer likes next is: what would you do differently if you knew all of this? The answer is nothing. You compare values with ==, you use is only for None and your own sentinels, and you treat identity as a debugging aid. Knowing the cache exists helps you read a surprising REPL result without panicking, and that is its whole value.

Q9. "What does frozendict add in 3.15, and how does it compare with MappingProxyType and a frozen dataclass?"

Reveal answer

The real test Whether you separate "a read-only view of someone else's dict" from "a dict that cannot change at all".

Strong answer Python 3.15 adds frozendict as a built-in (PEP 814). It is an immutable mapping type: no item assignment, no update, and it is hashable when its keys and values are hashable. That means it can be a dict key or a set member.

types.MappingProxyType is different. It is a read-only view onto a dict. You cannot change the data through the proxy, but whoever owns the underlying dict can, and the proxy shows the change. It is also not hashable.

A frozen dataclass is a fixed set of named fields, not a general mapping. It gives attribute access and type hints. Use it when the keys are known in advance, and frozendict when they are data.

So: need a hashable, truly immutable mapping with arbitrary keys, use frozendict on 3.15+. Need to expose an internal dict read-only without a copy, use MappingProxyType. Need typed named fields, use a frozen dataclass.

Picture it The three side by side, run on 3.15.0rc1.

The setup: Make each one, try to change it, and change the source dict behind the proxy.

q09_frozendict.py · Python 3.15.0rc1runs offline
from types import MappingProxyType
from dataclasses import dataclass, FrozenInstanceError

src = {"a": 1}
fd = frozendict(src)                       # built-in on 3.15
mp = MappingProxyType(src)

src["b"] = 2                               # change the source afterwards
print("frozendict :", fd)                  # unaffected: it copied
print("proxy      :", dict(mp))            # shows the change: it is a view

for label, obj in (("frozendict", fd), ("proxy", mp)):
    try:
        obj["z"] = 9
    except TypeError as e:
        print(f"{label} write ->", e)

print("hashable frozendict as key:", {fd: "ok"})
try:
    hash(mp)
except TypeError as e:
    print("hash(proxy) ->", e)

@dataclass(frozen=True)
class Fees:
    delivery: int = 3
f = Fees()
try:
    f.delivery = 5
except FrozenInstanceError as e:
    print("dataclass write ->", type(e).__name__, e)
print("is a dict subclass?", isinstance(fd, dict))
output · Python 3.15.0rc1runs offline
frozendict : frozendict({'a': 1})
proxy      : {'a': 1, 'b': 2}
frozendict write -> 'frozendict' object does not support item assignment
proxy write -> 'mappingproxy' object does not support item assignment
hashable frozendict as key: {frozendict({'a': 1}): 'ok'}
hash(proxy) -> unhashable type: 'dict'
dataclass write -> FrozenInstanceError cannot assign to field 'delivery'
is a dict subclass? False

What you see: the frozendict kept the data it was given, the proxy followed the source dict, both refuse writes, only the frozendict can be a key, and a frozen dataclass raises FrozenInstanceError.

Why: frozendict owns its data; MappingProxyType borrows it. Ownership is the whole difference.

Land it I pick frozendict for an immutable hashable mapping (3.15+), MappingProxyType for a read-only window onto a dict I own, and a frozen dataclass when the fields are fixed.

Likely follow-ups
"What do I do on Python 3.12 or 3.14 where there is no frozendict?"

On 3.12 and 3.14 the built-in does not exist, so you choose by what you need.

  1. Read-only view of data you own: MappingProxyType(dict(data)) gives a read-only mapping over a private copy. Nobody holding the proxy can edit it, and nobody else has the copy.
  2. A hashable key: A proxy is not hashable. Use tuple(sorted(d.items())) or frozenset(d.items()), which works when the values are hashable, and rebuild a dict when you need lookups.
  3. A drop-in type: A third-party package called frozendict has existed for years with a similar API.

Before depending on the built-in frozendict, check the 3.15 documentation for what it supports, because the third-party version may differ in details. If your code has to run on 3.12 as well, I would hide the choice behind one small function so a later switch changes one line.

"Is a frozendict deeply immutable?"

No. It stops changes to the mapping itself, not to the objects stored as values. frozendict(a=[1]) still holds a mutable list, and anyone with the list can change it. The run below is from the 3.15 release candidate, and shows what hashing does with such a value.

q09_frozen.py (3.15.0rc1 output, last line)runs offline
TypeError: unhashable type: 'list'

The mapping refuses to hash because one of its values cannot be hashed. A frozendict whose values are all hashable, for example frozendict(a=1), hashes fine and gives equal hashes for equal contents.

For real deep immutability, make the values immutable too: numbers, strings, tuples, frozensets and other frozen things. A frozendict of tuples is immutable all the way down. I treat "frozen" as a property to check at every level, not one I get from the outer type.

"Why not just document that nobody should change the dict?"

Because documentation does not stop a thread, a plugin or a developer who joins in six months. A comment that says "do not modify" is a rule only people who read it follow. Mutable shared config is a bug waiting for the Q7 incident, where one tenant's edit reached every tenant.

An immutable type changes where the failure happens. Instead of a customer reporting a wrong price three hours later, the offending line raises TypeError in the developer's test run, with a stack trace that points at the exact edit. That is the cheapest possible place to find the bug.

There is also a performance side: a truly immutable object can be shared across threads without a lock, and across tenants without a copy. With a mutable dict you need either a lock or a defensive copy on every handoff.

So my argument for the extra type is the one I would make for final in Java: make the compiler, or here the runtime, enforce what the team agreed in conversation.

"Is it a subclass of dict?"

In the 3.15 release candidate I ran, no. isinstance(fd, dict) is False, while isinstance(fd, collections.abc.Mapping) is True. The run printed those two values on one line:

q09_frozen.py (3.15.0rc1 output, first line)runs offline
False True

The consequence is that code which checks isinstance(x, dict) will reject a frozendict. This catches people who write JSON encoders and validators that special-case dict.

The habit that avoids it is to accept collections.abc.Mapping in function signatures and checks. Then callers can pass a dict, a MappingProxyType, a frozendict or a custom mapping, and your function does not care. I would also keep an eye on the final 3.15 documentation, since release candidates can still change in small ways.

Q10 · Design. "Design an immutable Money value object. Which tools do you use and why?"

Reveal answer

Strong answer A money value has two parts, an amount and a currency, and it must never change after creation. I build it with @dataclass(frozen=True, slots=True), store the amount as decimal.Decimal, and round once, in __post_init__.

Frozen gives immutability, plus __eq__ and __hash__ for free, so Money can be a dict key and safe to share across threads. slots removes the per-instance __dict__ and saves memory if you hold millions. Decimal avoids binary floating point, where 0.1 + 0.2 is not 0.3.

Rules I enforce: reject float input, because the damage is done before we ever see it; refuse to add different currencies; round with a named rule (banker's rounding, ROUND_HALF_EVEN, or half-up as the business requires) to two places; return a new object from every operation.

Alternatives and when to switch: integer cents are fastest and simplest when you only add and subtract in one currency. A library such as py-moneyed helps with many currencies. Use plain Decimal fields without a class only for throwaway scripts.

Picture it The value object, its behaviour, and the ways it refuses to be misused.

The setup: A Money class that rounds on creation, refuses floats and mixed currencies, and cannot be edited.

q10_money.py · Python 3.14runs offline
from dataclasses import dataclass, FrozenInstanceError
from decimal import Decimal, ROUND_HALF_EVEN

CENT = Decimal("0.01")

@dataclass(frozen=True, slots=True)
class Money:
    amount: Decimal
    currency: str = "USD"

    def __post_init__(self):
        if isinstance(self.amount, float):
            raise TypeError("pass a str or Decimal, not float")
        q = Decimal(self.amount).quantize(CENT, ROUND_HALF_EVEN)
        object.__setattr__(self, "amount", q)     # only allowed inside init

    def __add__(self, other):
        if not isinstance(other, Money):
            return NotImplemented
        if other.currency != self.currency:
            raise ValueError(f"cannot add {self.currency} and {other.currency}")
        return Money(self.amount + other.amount, self.currency)

    def times(self, qty: int) -> "Money":
        return Money(self.amount * qty, self.currency)

price = Money("19.995")
print(price, "<- rounded half-even to cents")
print(price + Money("0.01"), "|", price.times(3))
print("0.1 + 0.2 as float:", 0.1 + 0.2, "| as Money:", Money("0.1") + Money("0.2"))
print("hashable:", {Money("5"): "five"}, "| equal:", Money("5.00") == Money("5"))
for label, fn in (("edit", lambda: setattr(price, "amount", 1)),
                  ("float", lambda: Money(0.1)),
                  ("mixed currency", lambda: price + Money("1", "EUR"))):
    try:
        fn()
    except (FrozenInstanceError, TypeError, ValueError) as e:
        print(f"{label:15}->", type(e).__name__, e)
output · Python 3.14runs offline
Money(amount=Decimal('20.00'), currency='USD') <- rounded half-even to cents
Money(amount=Decimal('20.01'), currency='USD') | Money(amount=Decimal('60.00'), currency='USD')
0.1 + 0.2 as float: 0.30000000000000004 | as Money: Money(amount=Decimal('0.30'), currency='USD')
hashable: {Money(amount=Decimal('5.00'), currency='USD'): 'five'} | equal: True
edit           -> FrozenInstanceError cannot assign to field 'amount'
float          -> TypeError pass a str or Decimal, not float
mixed currency -> ValueError cannot add USD and EUR

What you see: 19.995 rounds to 20.00, the float line prints 0.30000000000000004 while Money prints 0.30, equal amounts hash equally, and each misuse raises a named error.

Why: frozen=True blocks assignment after init, so __post_init__ uses object.__setattr__ once to store the rounded value.

Java · Spring

A record is the same idea.

Money.javaruns offline
public record Money(
    BigDecimal amount,
    String currency) {
  public Money {
    amount = amount.setScale(2,
        RoundingMode.HALF_EVEN);
  }
}

Python

Frozen dataclass with Decimal.

money.pyruns offline
@dataclass(frozen=True, slots=True)
class Money:
    amount: Decimal
    currency: str = "USD"
    def __post_init__(self):
        q = Decimal(self.amount).quantize(
            CENT, ROUND_HALF_EVEN)
        object.__setattr__(self, "amount", q)

The shift: Java gives you BigDecimal and records; Python gives you Decimal and frozen dataclasses. In both, the amount is rounded once and never edited. See the value-object idiom.

Land it I model Money as a frozen, slotted dataclass over Decimal, round once on construction, and make every operation return a new value.

Likely follow-ups
"Why not store cents as an integer?"

Integer cents are a good choice and often faster, with one catch that shows up the moment you multiply.

  1. Where they shine: Adding and subtracting amounts in one currency is exact and quick, and cents fit in a normal int. A database column of BIGINT cents is simple and has no rounding surprises.
  2. Where they hurt: Tax, discounts and exchange rates are multiplications by fractions, so a result like 164.9175 cents appears, and you must decide the rounding rule at every such step. It is easy to forget one.
  3. Where Decimal helps: Decimal keeps exact decimal arithmetic and lets you round once, at a visible place, with a named rule.

My choice: integer cents when the system is mostly sums and the currency is fixed, Decimal when percentages and several currencies are everywhere. Here is the arithmetic for 8.25 % tax on 19.99:

worked exampleruns offline
19.99 -> 1999 cents
1999 x 825 / 10000 = 164.9175 cents   (not a whole number)
round to nearest -> 165 cents         (a rule you must choose and apply every time)
"Why does Decimal(0.1) print a long number?"

Because 0.1 as a float is already not one tenth. A float stores a binary fraction, and 0.1 has no exact binary form, so the nearest float is slightly more. Decimal(0.1) faithfully copies that exact stored value. The run shows what it holds.

q10_round.py (output, last line)runs offline
0.1000000000000000055511151231257827021181583404541015625

Decimal("0.1") starts from the text and is exactly one tenth. The two constructors look similar and do very different things: one preserves an error that already happened, the other avoids it.

That is why the Money class refuses floats. If a float enters, the error entered before our code ran, and rounding afterwards only hides it. I reject float in __post_init__ with a clear message and accept Decimal, int or str. At system edges, such as JSON parsing, I read numbers as strings, or use a parser option that yields Decimal.

"What is banker's rounding and why choose it?"

ROUND_HALF_EVEN rounds an exact half to the nearest even digit, so errors cancel out over many roundings instead of always going up. Half-up always rounds a half upward, which over a million invoices pushes the total in one direction by a small amount. The run uses strings so the values are exact.

q10_round.py (output)runs offline
value  half_even  half_up
2.665  2.66       2.67
2.675  2.68       2.68
2.685  2.68       2.69

In the first row, 2.665 is exactly a half, and half-even picks 2.66 (even last digit). In the second, 2.675 goes to 2.68, which is also even, so both rules agree. The third differs again.

Some businesses and tax rules require half-up. Rounding is a policy, so I make it a named constant in one place, test it with halves, and never leave it to a default.

"Is slots=True worth it for money?"

If you hold a few objects, you will not notice. If a report builds ten million of them, slots cut memory sharply. On 3.14 I measured one million small instances at about 104.5 MB without slots and 64.4 MB with them (Q33 shows the full measurement), because each instance no longer carries a per-instance dict.

A second benefit is safety. A slotted class has a fixed list of attributes, so a typo such as price.amout = 3 raises AttributeError instead of silently creating a new attribute that nothing reads.

The cost is that you cannot add attributes later, and some tools that expect __dict__ do not work with slotted objects. Pickling, weak references and multiple inheritance each need a small extra step. With @dataclass(frozen=True, slots=True) the library takes care of most of this.

For a value object that is a feature, not a limitation: the fields are fixed on purpose. I would still leave slots off a rarely created config object, where simplicity wins.

Drill · Memory management

These questions test whether you can explain reference counting and the cycle collector, and then use tracemalloc, gc and weakref to find a real leak rather than guess.

Q11. "How does CPython free memory? Explain reference counting and the cycle collector."

Reveal answer

The real test Whether you say "most objects die the instant their count hits zero" and "the collector exists only for cycles", not "Python has a garbage collector like Java".

Strong answer Every CPython object carries a reference count: the number of names, containers and temporaries pointing at it. When a new reference appears the count goes up; when one goes away it goes down. At zero, CPython frees the object immediately, on the same thread, in the same instant.

That is deterministic and cheap to reason about. A local variable's object is freed when the function returns, a file object is closed when its last reference drops, and no pause is needed.

Reference counting cannot free a cycle. If a points at b and b points at a, each keeps the other's count at 1 even after your code lost both names. A second system, the cyclic garbage collector, periodically searches for groups of objects that only reference each other and are unreachable from your program, and frees them.

So the answer has two layers: counting handles almost everything at once, and the cycle collector sweeps the leftovers on a schedule.

Picture it An object freed the moment its count hits zero, and a cycle that survives until gc.collect().

The setup: A class that prints from __del__, used once alone and once in a two-object cycle.

q11_refcount_cycle.py · Python 3.14runs offline
import gc

class Noisy:
    def __init__(self, name):
        self.name = name
    def __del__(self):
        print(f"  freed {self.name}")

print("1) count reaches zero")
x = Noisy("A")
x = None                       # last label removed
print("  (line after x = None)")

print("2) two objects in a cycle")
a, b = Noisy("B1"), Noisy("B2")
a.other, b.other = b, a        # a -> b -> a
a = b = None                   # both labels gone, counts stay at 1
print("  (line after a = b = None: nothing freed yet)")
print("  gc.collect() found", gc.collect(), "unreachable objects")
print("generation thresholds:", gc.get_threshold())
output · Python 3.14runs offline
1) count reaches zero
  freed A
  (line after x = None)
2) two objects in a cycle
  (line after a = b = None: nothing freed yet)
  freed B1
  freed B2
  gc.collect() found 2 unreachable objects
generation thresholds: (2000, 10, 10)

What you see: A is freed before the next line prints. B1 and B2 are freed only when gc.collect() runs. The collector reports how many objects it reclaimed.

Why: counts never reached zero for the cycle members because they referenced each other. Only a graph search from the collector can see that nothing outside the cycle reaches them.

Reference counting

Freed at zero, instantly.

refcount.pyruns offline
x = Noisy("A")
x = None
# __del__ runs on this line

Cycle collector

Freed later, in batches.

cycle.pyruns offline
a.other, b.other = b, a
a = b = None
# nothing yet; gc.collect()
# or the next gen-0 run

The shift: Two mechanisms: immediate and exact for acyclic data, periodic and approximate for cycles.

Land it I explain that CPython frees by reference count at once and runs a separate cycle collector for the objects that count alone can never free.

Likely follow-ups
"What does sys.getrefcount(x) return, and why is it one higher than I expect?"

It returns the object's reference count, and the number is always one higher than the labels you can see. The reason is that passing x to the function creates a temporary extra reference for as long as the call runs.

q11_refcount.py (output)runs offline
2     only the name a, plus the call's own argument
3     after b = a: two names, plus the argument
2     after del b

The first line makes the +1 visible: a list with a single name reports 2. After b = a the count is 3, and del b brings it back to 2. In Q1 the list had the labels a and b, so the call printed 3.

I use getrefcount for demonstrations and for debugging a leak, such as finding out how many things still point at an object that should have died. I never use it in program logic. The number depends on the interpreter, temporary values and, in recent versions, whether the object is immortal and has a fixed count.

"How does the cycle collector know what is garbage?"

It works only on container objects, because only containers (lists, dicts, instances, tuples) can hold references to other objects. Plain numbers and strings cannot form a cycle, so they are not tracked.

For every tracked object it first copies the reference count into a scratch field. Then, for each object, it subtracts one for every reference that comes from another tracked object in the same group. What remains is the number of references from outside the group, such as a local variable, a global or a stack frame.

If the remainder is above zero, something outside points at the object, so it is alive, and everything reachable from it is alive too. Objects whose whole count is explained by other tracked objects, and which nothing alive reaches, are unreachable. The collector frees them together.

Example: after a.o = b; b.o = a; del a, b, each object has count 1, and that 1 comes from the other. Both drop to 0 and are freed.

"Does it matter that the count is updated on every assignment?"

Yes, it is a real cost, and it explains three things that people ask about separately.

  1. It dirties memory pages: Every time code passes an object around, the count in its header is written. After fork, a child process shares the parent's memory pages until one side writes, so counting slowly copies pages, and a pre-fork server's shared memory un-shares over time (Q13).
  2. It is why the GIL existed (Q75): If two threads changed counts at the same time without protection, counts would be wrong and objects would be freed too early or never. One global lock was the simple fix.
  3. Immortal objects help: Since 3.12, objects such as None, small ints and some interned strings are marked immortal, and their counts are never updated. That removes writes for the most shared objects, and it also helps free-threaded builds.

So the count is cheap per operation but not free. For a hot loop on one object, the write is why memory traffic can matter more than arithmetic.

"Did anything change in recent versions?"

Not in the way you might hope. Python 3.14.0 to 3.14.4 shipped an incremental cycle collector, which worked in smaller slices to shorten pauses. Reports of higher memory use led to its removal in 3.14.5, which returned to the 3.13 generational collector. 3.15 keeps that one, and I would check the 3.15 What's New for any later change.

So the honest answer for a current interpreter is that the collector behaves as it did in 3.13, and I would measure pause times, not assume them. A gc.callbacks hook (Q17) shows how long each collection takes.

The two-layer design itself, counting plus a cycle collector, is unchanged. The other recent change that does matter is immortal objects in 3.12, which removed counting writes for common objects.

Q12 · Scenario. "A long-running worker grows from 200 MB to 3 GB over a day. How do you find the leak?"

Reveal answer

Strong answer I follow a fixed order, because "memory grows" has three different causes: a real Python leak (something keeps references), fragmentation (freed but not returned to the OS, Q13), or a native-extension leak.

First, confirm the growth is in Python objects. Start tracemalloc in a staging copy, take a snapshot at start and another after an hour of load, and call compare_to on the two. It lists the source lines whose allocations grew the most. If tracemalloc's total grows with RSS, it is a Python leak; if RSS grows but tracemalloc stays flat, suspect native code or fragmentation.

Second, read the top lines. The usual suspects are an unbounded dict or list used as a cache, a functools.lru_cache on a method (Q50), a logger or metrics registry with per-request labels, a list of tasks never removed, and an exception traceback stored for later, which keeps every frame alive.

Third, fix and prove it. Bound the cache, use weak references (Q15), remove completed items, and rerun the same load. The snapshot diff after the fix should be flat.

Picture it A deliberately leaky cache and the line tracemalloc points at.

The setup: A request handler stores every response in a module-level dict and never removes anything.

q12_tracemalloc_leak.py · Python 3.14runs offline
import tracemalloc

_cache = {}                                  # ❌ TRAP: never evicts

def handle(request_id):
    _cache[request_id] = f"resp-{request_id}-" + "x" * 1000   # a 1 KB response

tracemalloc.start()
before = tracemalloc.take_snapshot()
for i in range(20_000):
    handle(i)
after = tracemalloc.take_snapshot()

for stat in after.compare_to(before, "lineno")[:2]:
    print(stat)
current, peak = tracemalloc.get_traced_memory()
print(f"traced now: {current / 1e6:.1f} MB, peak {peak / 1e6:.1f} MB")
output · Python 3.14runs offline
q12_tracemalloc_leak.py:6: size=20.6 MiB (+20.6 MiB), count=20001 (+20001), average=1081 B
q12_tracemalloc_leak.py:10: size=617 KiB (+617 KiB), count=19743 (+19743), average=32 B
traced now: 22.3 MB, peak 22.3 MB

What you see: the top line is the _cache[request_id] = ... line in handle, with its size growth (about 20 MB for 20,000 entries) and a count of allocations. The second line is the loop that creates the integer ids the dict keeps as keys.

Why: compare_to subtracts two snapshots and ranks source lines by growth, so the leaking line rises to the top without guessing.

Land it I confirm with tracemalloc that Python objects are growing, diff two snapshots to find the line, fix it with a bound or a weak reference, and re-run the same load to prove the line went flat.

Likely follow-ups
"What if tracemalloc is too slow to run in production?"

It slows the program down noticeably and adds memory, because it records a traceback for every allocation it tracks. The slowdown is large enough that I never switch it on for all production traffic. Run it on a canary instance, or in staging with replayed traffic.

For production, I track RSS over time and a cheap count of live objects by type. gc.get_objects() grouped with collections.Counter(type(o).__name__ for o in gc.get_objects()) is a few lines and cheap enough to run on demand, for example from an admin endpoint. It will not give a line number, but it tells you which class is multiplying, such as 4 million Session objects.

The two views complement each other. The counter tells me what, and a short tracemalloc run in staging, filtered to that module, tells me where.

"How do I tell a leak from normal growth?"

Normal growth plateaus, and a leak keeps climbing in proportion to work done. A cache warms up, fills to its limit and stops. A leak adds a little with every request, so RSS rises as a straight line.

I plot RSS against requests served, not against clock time, because quiet hours would otherwise look like stability. If the slope flattens, it is a cache or a pool. If it keeps its slope, something retains one object per request.

Two more checks. First, look across restarts: a graph that resets to 200 MB after each deploy and climbs the same way is a leak, not a load pattern. Second, check whether a forced gc.collect() changes anything, because the growth may be cycles that have not been collected yet. A leak of 1 KB per request at 100 requests per second is 8.6 GB a day, which is how a harmless-looking line produces a 3 GB process.

"What if the leak is inside a C extension?"

Then tracemalloc will not see it, so I switch tools in three steps.

  1. Confirm: RSS grows while the tracemalloc total stays flat. That says Python's own allocator is not where the memory goes.
  2. Use a native profiler: memray can trace native allocations too, and valgrind or heaptrack work at the C level. They are slower, so I run them on a copy of the service with a small, repeatable load.
  3. Look for the usual cause: A C extension that keeps buffers until you call a close() you forgot, a connection or image object held by a cycle that is only collected late, or a known bug in a version of the library.

I also read the changelog of the extension, because a leak that other people hit is usually fixed upstream. If nothing helps, recycling the worker is a legitimate stopgap while the cause is found.

"What if the memory is held by reference cycles, not a cache?"

Call gc.collect() and watch two numbers: the return value and the RSS. The call returns the number of unreachable objects it found. If that number is large and the memory drops, cycles were waiting for the collector.

The fix then is to break the cycles at the source. Use weakref for back-pointers such as a child pointing to its parent, avoid storing exceptions with their tracebacks on long-lived objects, and close resources explicitly instead of waiting for a collector. Tuning thresholds is a second choice.

If gc.collect() returns a small number and memory does not drop, the objects are still referenced from somewhere. That is the cache case, and the tracemalloc snapshot diff points straight at the line that adds them. Counting by type before and after the collect keeps this honest: I want to see the count of one class fall, not just a feeling that it should.

Q13. "Why can a Python process's memory (RSS) stay high after the objects are freed?"

Reveal answer

Strong answer Freed does not mean returned to the operating system. CPython hands small objects (512 bytes or less) out of its own allocator, pymalloc, which asks the OS for big blocks called arenas (256 KB in older versions, 1 MiB in newer ones) and carves them into pools for each size class.

When objects die, their slots go back to pymalloc's free lists, not to the OS. An arena goes back to the OS only when every slot in it is free. One surviving object pins the whole arena.

That is fragmentation: if you allocate a million objects and keep 1 in 100, the survivors are scattered across nearly every arena, so almost nothing can be released, even though 99 % of the objects are gone.

Big objects (above 512 bytes) go straight to the system malloc, which often does return large blocks to the OS. So a freed 300 MB buffer vanishes from RSS, while a freed million small objects may not.

Picture it RSS after freeing everything, freeing 99 %, and freeing one big buffer.

The setup: Read VmRSS from /proc/self/status at each step (Linux).

q13_rss_fragmentation.py · Python 3.14runs offline
import gc

def rss_mb():
    with open("/proc/self/status") as f:
        for line in f:
            if line.startswith("VmRSS"):
                return int(line.split()[1]) // 1024

class Rec:
    def __init__(self, i):
        self.i = i
        self.p = (i, i + 1)

print("start                      :", rss_mb(), "MB")
objs = [Rec(i) for i in range(1_000_000)]
print("1M small objects allocated :", rss_mb(), "MB")
keep = objs[::100]                      # keep 1 object in 100
del objs; gc.collect()
print("freed 99 %, kept 1 %       :", rss_mb(), "MB   <- still high")
del keep; gc.collect()
print("freed the rest             :", rss_mb(), "MB")
big = bytearray(300 * 1024 * 1024)
print("300 MB buffer held         :", rss_mb(), "MB")
del big
print("300 MB buffer freed        :", rss_mb(), "MB")
output · Python 3.14runs offline
start                      : 11 MB
1M small objects allocated : 233 MB
freed 99 %, kept 1 %       : 225 MB   <- still high
freed the rest             : 12 MB
300 MB buffer held         : 312 MB
300 MB buffer freed        : 12 MB
# measured on the course machine; your numbers will differ

What you see: with 99 % freed the RSS barely moves, because survivors pin the arenas. Only when the last survivors die does RSS fall. The single big buffer comes back instantly.

Why: small objects live in arenas that are returned only when completely empty; large blocks use malloc/free directly.

Land it I say freed memory goes back to pymalloc's free lists, not the OS, and arenas are released only when completely empty, so fragmentation keeps RSS high.

Likely follow-ups
"So what do I do about a worker that stays large?"

Reduce fragmentation at the source, and if that is not enough, recycle the process.

  1. Work in batches: Let each batch's small objects be created and freed together, so whole arenas become empty. Objects that live for different times mixed in one arena are what pin it.
  2. Use compact structures: Put long-lived data into arrays, tuples or __slots__ classes. Fewer, bigger objects mean less scattering. Load read-only tables once, at startup, before the first request.
  3. Recycle workers: Let a worker exit after N jobs and the operating system takes back everything. Gunicorn's max_requests and Celery's max_tasks_per_child do exactly this.

I would add jitter, for example max_requests_jitter in Gunicorn, so all workers do not restart at the same moment. Recycling is blunt, but it is predictable, and a worker that restarts every few hours does not need a perfect allocator.

"Does gc.collect() shrink RSS?"

Not by itself. gc.collect() frees unreachable cycles, which returns their slots to pymalloc's free lists. RSS shrinks only if that happens to leave whole arenas empty, and after a long run it usually does not. A million objects freed from a million-object heap with survivors spread through it can leave RSS almost unchanged.

People sometimes call gc.collect() in a loop hoping for smaller memory. In my experience it wastes time: each call scans all tracked objects, so on a large heap it costs real milliseconds.

What does help is measuring what kind of memory you have. If the count of Python objects falls and RSS does not, the memory is sitting in pymalloc's free lists or in the C allocator. Then the answer is to change the allocation pattern, or recycle, not to collect more often.

"What is malloc_trim and should I use it?"

On Linux with glibc, malloc_trim(0) asks the C allocator to hand free pages at the top and middle of its heap back to the operating system. You can call it with ctypes: ctypes.CDLL("libc.so.6").malloc_trim(0). It is not Python-specific.

It helps for memory that came from malloc directly: big buffers, native-extension data, and Python objects above 512 bytes. It does nothing for a pymalloc arena that is still partly used, because pymalloc manages that memory itself.

I treat it as a workaround for native fragmentation. I would try it only after measuring that native memory, not Python objects, is the problem, for instance when tracemalloc is flat and RSS is large. It is also glibc-specific, so it will not help on macOS or Alpine's musl. The simpler and more portable fix is still to recycle workers.

"How does this relate to fork and copy-on-write?"

A forked child shares the parent's memory pages until one side writes to them, which is called copy-on-write. The trouble is that Python writes even when you only read. Each object's reference count lives in its own header, so using an object changes its count, and the page it lives on is copied for that child.

A pre-fork server therefore starts with, say, 300 MB shared, and slowly drifts towards 300 MB per worker. The collector adds to this: when it scans objects it also writes to their headers.

gc.freeze() (Q17) moves everything alive at that moment into a permanent set that the collector ignores, so collections do not touch those headers. It does not stop reference-count writes, so it slows the un-sharing, it does not end it. I call it just before forking, then measure shared versus private memory with smem or /proc/<pid>/smaps before claiming a win.

Q14. "What does sys.getsizeof measure, and why does it mislead for containers?"

Reveal answer

Strong answer sys.getsizeof(x) returns the size in bytes of the object itself, plus any garbage-collector header, and nothing it points at. It is a shallow size.

For a list it reports the list's own memory: a header plus an array of 8-byte pointers. The items those pointers lead to are separate objects, and getsizeof does not add them. A list of 1,000 strings of 100 characters reports about 9 KB, while the strings together can be 100 KB or more.

So it undercounts every container: lists, dicts, sets, tuples, class instances. It also counts shared objects once per place you ask, so summing sizes of things that share data double counts.

For a true total, either walk the object graph and add up unique ids (a recursive sizeof helper), or measure at the allocator with tracemalloc, which reports what the program actually allocated, including all the pieces.

Picture it getsizeof of a list of strings next to the real total.

The setup: Build 1,000 strings of 100 characters each and compare three numbers.

q14_getsizeof.py · Python 3.14runs offline
import sys, tracemalloc

tracemalloc.start()
base, _ = tracemalloc.get_traced_memory()
items = ["row-%04d-" % i + "x" * 90 for i in range(1000)]     # 1,000 strings, 100 chars each
real, _ = tracemalloc.get_traced_memory()

shallow = sys.getsizeof(items)
deep = shallow + sum(sys.getsizeof(s) for s in items)
print("getsizeof(list)            :", shallow, "bytes")
print("list + each string (deep)  :", deep, "bytes")
print("tracemalloc, what was held :", real - base, "bytes")
print("one string                 :", sys.getsizeof(items[0]), "bytes for 100 characters")
output · Python 3.14runs offline
getsizeof(list)            : 8856 bytes
list + each string (deep)  : 148856 bytes
tracemalloc, what was held : 149264 bytes
one string                 : 140 bytes for 100 characters

What you see: getsizeof(list) is 8,856 bytes while the real memory is about 17 times that. The 'one string' line shows why: each 100-character string is 140 bytes, and there are 1,000 of them. Adding every string's size gets close to what tracemalloc saw, with a little difference from allocator rounding and the temporary strings.

Why: a list is an array of pointers; the objects at the other end belong to the strings.

getsizeof

Shallow: just the pointer array.

shallow.pyruns offline
sys.getsizeof(items)
# 8856 bytes for 1,000 items

tracemalloc

Everything allocated.

deep.pyruns offline
tracemalloc.start()
items = build()
tracemalloc.get_traced_memory()
# about 150 KB

The shift: Ask the allocator what the program holds, not the object what it weighs by itself.

Land it I use getsizeof only for a single flat object, and tracemalloc or a recursive walk for anything that contains other objects.

Likely follow-ups
"How do I write a deep size function?"

Write a small recursive walk, and keep a record of what you have counted.

  1. Keep a seen set: Start with seen = set() of id(obj). Before measuring an object, skip it if its id is in the set; otherwise add it. This stops cycles and avoids counting a shared object twice.
  2. Add the shallow size: For each new object add sys.getsizeof(obj).
  3. Recurse into the parts: For a dict, walk keys and values. For a list, tuple, set or frozenset, walk the items. For an instance, walk its __dict__ and any slots.

That is about fifteen lines. Libraries such as pympler.asizeof already do it, including the awkward cases, so I use one for anything beyond a quick check. I still confirm with tracemalloc, because a walk can miss memory held by C extensions that do not expose their contents.

"Why is an empty list not zero bytes?"

Because it has a header: a type pointer, a reference count, a length and a capacity. In current versions an empty list is 56 bytes. Then it over-allocates as it grows, so the reported size jumps in steps rather than by 8 bytes per item. The run appends one item at a time and prints the size each time it changes.

q14_list.py (output: length, then bytes)runs offline
0 56
1 88
5 120
9 184
17 248
25 312
33 376

The first append reserves room for 4 items (88 bytes), and after that the list grows by roughly an eighth plus a constant. That is how append stays cheap on average. getsizeof shows capacity, not length, so 8 * len + 56 is only a lower bound.

"Why does a dict look so small too?"

It is the same shallow measurement. sys.getsizeof({}) reports the memory of the hash table itself, a few dozen bytes for an empty dict, and grows as it resizes. The keys and values are separate objects, and getsizeof does not add them.

A dict of 1,000 short strings reports tens of kilobytes for the table, while the 1,000 keys and 1,000 values add tens of kilobytes more. The total can easily be twice the reported number or higher, and it depends on how many of the strings are shared.

Instances of normal classes are the most misleading of all. The instance object is small, its attribute storage is another object, and the attribute values are further objects. A class with three attributes can report about 48 bytes while really holding more.

This is why a shallow number can mislead a review. Before I believe a size, I ask what it includes.

"How would you use this in a code review?"

When someone writes "this structure is only 56 bytes", I ask how it was measured. I want a tracemalloc figure for the real data, with the number of objects in the denominator, so the claim reads "1M records, 190 MB traced, 190 bytes each".

That one line in the pull request is worth more than any estimate from getsizeof, because it answers the question the team actually has: how big will this be in production? It also gives the next engineer a baseline to compare against after a refactor.

My short checklist for a memory claim: it was measured on a sample large enough to include the real shapes, it counts the contents and not just the container, and it says which interpreter version produced the number. A figure that comes from getsizeof alone gets one comment from me: please re-measure with tracemalloc.

Q15 · Scenario. "A cache keyed by object keeps every object alive forever. Fix it."

Reveal answer

Strong answer A normal dict holds a strong reference to its keys and values, so as long as an entry exists the object cannot be freed. A cache of "extra data about this object" therefore turns every object into a permanent resident.

The fix is a weak reference: a reference that does not raise the reference count. When the last strong reference goes away, the object is freed and the weak reference becomes dead.

The standard tools are weakref.WeakValueDictionary (values held weakly: an entry disappears when its value is freed) and weakref.WeakKeyDictionary (keys held weakly). Pick by which side is the object you do not want to keep alive.

Limits: the object must be weak-referenceable (ordinary class instances are; int, str, list and dict instances are not, though subclasses are), and keys of a WeakKeyDictionary must be hashable. For caches with a size bound instead, use lru_cache (Q59).

Picture it A strong cache keeping an object alive, then a weak cache that lets go.

The setup: A Session object cached by id; delete the last outside reference and look at the cache.

q15_weakref_cache.py · Python 3.14runs offline
import weakref, gc

class Session:
    def __init__(self, sid):
        self.sid = sid

strong = {}
weak = weakref.WeakValueDictionary()

s1 = Session("s1")
strong["s1"] = s1
s2 = Session("s2")
weak["s2"] = s2

del s1, s2                                # drop the outside references
gc.collect()
print("strong cache keys:", list(strong))  # object still alive
print("weak cache keys  :", list(weak))    # entry vanished with the object

keep = Session("s3")
weak["s3"] = keep
print("while referenced :", list(weak))
del keep
print("after del        :", list(weak))
output · Python 3.14runs offline
strong cache keys: ['s1']
weak cache keys  : []
while referenced : ['s3']
after del        : []

What you see: the strong cache still has s1 after del. The weak cache lost s2 the moment nothing else referenced it, and s3 was present only while keep existed.

Why: a weak reference observes an object without owning a count, so it cannot keep it alive.

Strong dict

The cache owns the objects.

strong.pyruns offline
cache = {}
cache[obj.id] = obj
del obj
# still alive in cache

WeakValueDictionary

The cache only watches.

weak.pyruns offline
cache = WeakValueDictionary()
cache[obj.id] = obj
del obj
# entry removed automatically

The shift: Ownership decides lifetime. A cache should not own what it merely indexes. See the weakref cache idiom.

Land it I replace the strong dict with a WeakValueDictionary so the cache cannot keep an object alive, and I use a bounded lru_cache where I want a size limit instead.

Likely follow-ups
"When is a weak cache the wrong choice?"

When you want the cache to keep objects alive. Take an expensive lookup, such as parsing a config file or fetching a price list, where nobody else holds the result. A weak cache would drop each value as soon as you computed it, because the cache is the only reference and it does not count. You would pay for the lookup every time.

For that case you want a bounded strong cache, such as functools.lru_cache, where eviction is by use or by size and not by who else holds the object. The memory is bounded by the cache's limit.

Weak caches suit a different job: canonicalising or deduplicating live objects. For example, one Customer object per customer id while any code is still using it, so two parts of the program never hold two separate copies. When the last user lets go, the entry vanishes on its own. I ask one question to choose: does the value have an owner other than the cache? If yes, weak. If no, bounded strong.

"Why can I not weak-reference an int or a list?"

Built-in types without a __weakref__ slot cannot be weakly referenced. This is a deliberate saving: tiny objects such as ints do not carry the extra pointer. The run shows the messages, and two cases that work.

q15_weak.py (output, first lines)runs offline
TypeError: cannot create weak reference to 'int' object
TypeError: cannot create weak reference to 'list' object
True
S TypeError: cannot create weak reference to 'S' object
SW ok

A subclass of list works (the True line), because a class defined in Python gets the slot automatically. A class with __slots__ loses it unless "__weakref__" is listed, shown by S and SW.

That is a frequent surprise when someone adds slots later (Q33): the class works for months, then a weak cache raises TypeError. My fix is to list __weakref__ in the slots, and to keep a test that puts an instance in a weak dictionary.

"What is weakref.finalize?"

It is the safe replacement for __del__, and it has a precise contract.

  1. The call: weakref.finalize(obj, callback, *args) registers callback(*args) to run when obj is freed. It lives outside the object, so it works for classes you do not own.
  2. The one rule: The callback must not hold a strong reference to obj, directly or through a bound method. If it did, obj could never die. Pass what it needs, such as a file descriptor or a path, as arguments.
  3. The extras: It runs at most once. You can call it yourself (f()), detach it with f.detach(), and it is run at interpreter exit by default, which you can switch off with f.atexit = False.

Use it to close a resource tied to an object's lifetime, for example removing a temporary directory when its owner object dies. Q16 explains why __del__ is dangerous.

"How does Java compare?"

Java has WeakReference, WeakHashMap and SoftReference, and the idea is the same: a reference that does not keep its target alive. The difference is timing. A Java weak entry disappears at some later garbage collection, whenever the collector next runs. A CPython weak entry disappears the moment the reference count reaches zero. The run shows it.

q15_weak.py (output, last two lines)runs offline
1
0

The first line is the dictionary length while o still exists, and the second is right after del o. No collector run is needed, because there was no cycle.

That determinism makes Python weak caches simple to test: delete, then assert. In Java you would call System.gc() and still not be sure. The catch is that a cycle delays the disappearance until the cycle collector runs.

Q16. "What does __del__ do, and why is relying on it dangerous?"

Reveal answer

Strong answer __del__ is a finalizer: CPython calls it when an object is about to be destroyed. It is not a destructor you control. Python does not promise when it runs, whether it runs at all, or in which thread.

In CPython, with no cycles, it runs right when the last reference goes (Q11), so it looks reliable in a simple test. That reliability disappears in three situations. If the object is in a reference cycle, it runs whenever the cycle collector finds it. If something keeps the object alive, such as a stored exception whose traceback holds the frame, it runs much later. And at interpreter shutdown it may not run, or may run with half the modules already torn down.

Two more traps: an exception raised inside __del__ is not propagated, it is printed and ignored, so failures are silent; and other Python implementations (PyPy, Jython) free objects at different times.

Do resource cleanup with with and try/finally, and use weakref.finalize when a cleanup must be tied to an object's lifetime without owning it.

Picture it A finalizer error that disappears, and an object that outlives its function because a traceback is saved.

The setup: A Conn class whose __del__ raises, and a function that fails while holding one.

q16_del_traps.py · Python 3.14runs offline
import sys

sys.unraisablehook = lambda u: print("  (ignored, not raised):", u.exc_value)

class Conn:
    def __init__(self, n):
        self.n = n
    def __del__(self):
        print(f"  __del__ runs for conn {self.n}")
        raise RuntimeError("boom inside __del__")

print("1) exception inside __del__")
c = Conn(1)
del c
print("  program carries on, nobody saw an error")

print("2) saved exception keeps the object alive")
def job():
    conn = Conn(2)
    raise ValueError("job failed")

try:
    job()
except ValueError as e:
    saved = e
print("  job() returned; conn 2 is NOT freed yet")
saved = None
print("  after dropping the saved exception")
output · Python 3.14runs offline
1) exception inside __del__
  __del__ runs for conn 1
  (ignored, not raised): boom inside __del__
  program carries on, nobody saw an error
2) saved exception keeps the object alive
  job() returned; conn 2 is NOT freed yet
  __del__ runs for conn 2
  (ignored, not raised): boom inside __del__
  after dropping the saved exception

What you see: the first __del__ error never reaches the program; the hook just reports it. In part two, conn 2 survives job() because the saved exception's traceback points at the frame that holds it, and it dies only after saved = None.

Why: the finalizer runs when the count hits zero, and tracebacks, caches and cycles all postpone that moment.

Fragile

Cleanup hidden in __del__.

frag.pyruns offline
class Conn:
    def __del__(self):
        self.sock.close()
# when? maybe never

Explicit

Cleanup you control.

expl.pyruns offline
with Conn() as conn:
    conn.query()
# __exit__ closes it here,
# even if query() raises

The shift: Put cleanup in the code path (with), not in the memory manager.

Land it I never put cleanup in __del__; I use with or try/finally, and weakref.finalize if a cleanup must follow an object's lifetime.

Likely follow-ups
"Why does it sometimes not run at interpreter exit?"

At shutdown, CPython tears the program down in a fixed order: it runs atexit callbacks, then clears modules and their globals, then frees what is left. An object that is still alive when its turn comes may be finalised late, or never if the process ends first.

The worse case is a __del__ that uses a global. By the time it runs, the module's globals may already have been cleared, so a name such as os or your own logger can be None, and you get AttributeError: 'NoneType' object has no attribute ... printed to stderr and ignored.

Because the order is an implementation detail, I do not write cleanup that has to happen at exit inside __del__. The reliable hook for "run this when the program ends" is atexit.register(func), which runs while everything is still intact. The reliable tool for "release when this block ends" is with.

"What is weakref.finalize doing better?"

weakref.finalize registers a callback tied to an object's death, without being a method of the object. That removes most of the traps of __del__. The shape is short:

finalize usage (snippet)runs offline
import weakref, shutil, tempfile

class Workspace:
    def __init__(self):
        self.path = tempfile.mkdtemp()
        self._fin = weakref.finalize(self, shutil.rmtree, self.path)

Notice that the callback receives self.path, a plain string, not self. If the callback referred to self, the object could never be freed. The finalizer runs at most once, can be run early with self._fin(), and is also run at interpreter exit by default. Because it is a separate object, an error in it does not depend on half-torn-down module state in the same way a method does.

I still prefer with for resources a function owns. I use finalize as a safety net for resources whose lifetime follows an object.

"Did __del__ and cycles ever break each other?"

Yes, and the story is a good example of why you should not depend on collector behaviour.

  1. Before 3.4: An object in a reference cycle that had a __del__ could not be freed. The collector did not know which finalizer to run first, so it put the objects in gc.garbage and left them there. Such cycles were a leak.
  2. PEP 442 (3.4): Finalisers now run safely for objects in cycles, and the cycle is collected. gc.garbage is rare today.
  3. What survives: Even now, the finaliser runs whenever the collector gets to the cycle, so "when" is unpredictable, and an object can be resurrected if the finaliser stores self somewhere.

The lesson is not to make cleanup depend on how the collector treats cycles. Break the cycles with weak references and close resources with with, and the whole question goes away.

"What does a good test for this look like?"

I assert that a resource is released after the with block exits, not after del or garbage collection. For a file-like helper, the test opens it in a with, leaves the block, and checks that closed is true or that the lock can be acquired again.

A test that calls gc.collect() to force finalisation is a warning sign: it shows that the production code depends on the memory manager to release something, which is exactly what the question warned about. It may pass on CPython and fail on PyPy, where freeing is later.

In review I search the diff for __del__ and ask what the explicit close path is. If there is none, the class needs a close() method and a __enter__ and __exit__ pair. If a finaliser is genuinely needed as a safety net, I ask for weakref.finalize plus a test that closes explicitly and a test that drops the object without closing.

Q17. "How do the cycle collector's generations work, and when would you call gc.freeze() or gc.disable()?"

Reveal answer

Strong answer The collector tracks container objects in generations. New objects start in the youngest generation. Each time the number of allocations minus deallocations passes a threshold (gc.get_threshold()), it scans the young generation; survivors are promoted to an older one, which is scanned much less often.

The idea, called the generational hypothesis, is that most objects die young, so scanning only new objects finds most garbage cheaply. Full collections over everything are rare and cost time proportional to the number of tracked objects, which is why a big heap makes the pauses longer.

Python 3.14.0 to 3.14.4 briefly used an incremental collector with two generations, but 3.14.5 reverted to the generational scheme described here, and 3.15 keeps it. The thresholds have differed between versions, so read them with gc.get_threshold() on your own interpreter.

gc.freeze() moves every currently tracked object into a permanent set that the collector ignores. Call it in a pre-fork server just before forking, so workers do not scan or touch the shared startup data (which keeps memory pages shared). gc.disable() switches automatic collection off; I use it only for short, allocation-heavy bursts or for a process I recycle often, and only when my code creates no cycles.

Picture it Collections per generation under churn, then freeze and disable.

The setup: Create 50,000 two-object cycles, count collections, freeze, then disable and churn again.

q17_gc_generations.py · Python 3.14runs offline
import gc

class N:
    pass

def churn(n):
    for _ in range(n):
        a, b = N(), N()
        a.other, b.other = b, a          # a garbage cycle every iteration

def collections():
    return [g["collections"] for g in gc.get_stats()]

print("thresholds:", gc.get_threshold(), "| enabled:", gc.isenabled())
gc.collect()
before = collections()
churn(50_000)
after = collections()
print("collections per generation during churn:", [b - a for a, b in zip(before, after)])

gc.freeze()
print("frozen objects:", gc.get_freeze_count())
gc.unfreeze()

gc.disable()
before = collections()
churn(50_000)
after = collections()
print("with gc disabled, collections:", [b - a for a, b in zip(before, after)])
print("garbage waiting:", gc.collect(), "objects freed by one manual gc.collect()")
output · Python 3.14runs offline
thresholds: (2000, 10, 10) | enabled: True
collections per generation during churn: [45, 4, 0]
frozen objects: 7336
with gc disabled, collections: [0, 0, 0]
garbage waiting: 101976 objects freed by one manual gc.collect()
# thresholds and counts differ between Python versions; these are 3.14.7

What you see: the youngest generation was collected 45 times, the next 4 times, the oldest not at all, and with gc.disable() nothing is collected until the manual call, which frees about 100,000 objects at once.

Why: the thresholds decide how often each generation is scanned; disabling removes the automatic trigger completely.

Land it I explain generations as "scan new objects often, old objects rarely", freeze before forking to protect shared pages, and disable only when I know there are no cycles and I measured a pause problem.

Likely follow-ups
"When is gc.freeze() actually useful?"

It is useful in a pre-fork server such as Gunicorn with preload_app. The parent imports the application, which creates hundreds of thousands of long-lived objects, then forks the workers. If nothing else happens, each child's first collection scans those objects and writes to their headers, which copies the memory pages the children were sharing.

The sequence that avoids it is: import the app, call gc.collect() once to clear garbage, call gc.freeze() so everything alive moves to a permanent set the collector ignores, then fork. Later collections in the children skip that set.

Instagram's engineering team described disabling or freezing the collector to save memory across forked workers. I would quote the idea, not their exact percentages, and measure my own app: compare shared and private memory per worker before and after. The freeze does not stop reference-count writes, so some un-sharing still happens (Q13).

"What is the risk of gc.disable()?"

If any code creates cycles, memory climbs, so the risk is a leak you caused on purpose.

  1. What creates cycles: Exceptions with tracebacks stored in variables, parent and child objects that point at each other, closures that refer to themselves, and some library internals. You often do not control all of them.
  2. What disable does: Automatic collections stop. Reference counting still frees everything that is not in a cycle, but cycles pile up until you call gc.collect().
  3. Safer variants: Raise the threshold, for example gc.set_threshold(100_000, 20, 20), so collections happen rarely. Or keep it disabled and call gc.collect() yourself at a quiet point, such as between batches.

I use disable only for short allocation-heavy bursts, and only after measuring that collection pauses were the problem.

"How do I see how long collections take?"

Register a function in gc.callbacks. It is called with "start" or "stop" and an info dict that has the generation and, at stop, the number collected. Timing the gap between the two gives each pause. The run below creates a two-object cycle and collects it.

q17_cb.py (output, Python 3.12)runs offline
start gen 2
stop gen 2 collected 2
(700, 10, 10)

The last line is gc.get_threshold() on that interpreter. In a service I would record the duration of each collection into a histogram and watch the generation-2 pauses.

If those pauses are in tens of milliseconds and line up with the tail-latency spikes in your metrics, the collector is a suspect. If they are microseconds, look elsewhere, such as locks, I/O or a slow query. The generation number tells you which kind it was: generation 0 collections are frequent and tiny, and generation 2 ones are the expensive full passes.

I keep the callback in production only while I am investigating, because it runs on every collection.

"Do generations matter for most services?"

Usually not. Most services have a modest number of container objects, and the collector does not show up in a profile. Generation tuning is something I reach for after evidence, not by habit.

It becomes visible when the process holds millions of long-lived container objects, such as a big in-memory index or a large parsed document. A full collection must visit every tracked object, so the pause grows with the heap, and a full pass over ten million objects can take long enough to be seen in tail latency.

In that case, shrinking the number of tracked objects usually helps more than tuning thresholds. Tuples that hold only numbers and strings are untracked after a first collection. Arrays, __slots__ classes and one big list of tuples instead of many small dicts all mean fewer things for the collector to visit. I would change the data shape first, then consider freeze or thresholds as a second step.

Q18. "JVM garbage collection versus CPython memory management — what are the real differences?"

Reveal answer

The real test Whether you can name the mechanism difference (tracing versus counting) and what each costs, not just "Java has a better GC".

Strong answer The JVM uses tracing collection. It does not count references at all. Periodically it starts from roots (stacks, statics), marks everything reachable, and treats the rest as garbage. The heap is divided into generations, and collectors (G1, ZGC, Shenandoah) trade throughput against pause time, with parts running concurrently with your code. Allocation is a pointer bump, which is very fast, and compaction removes fragmentation.

CPython uses reference counting plus a small cycle collector. Garbage is freed at the instant the last reference drops, so memory use is predictable and resources can be tied to scope. The cost is a write on every reference change, no compaction (so fragmentation, Q13), and work that cannot be sped up by more cores, which is a main reason the GIL existed.

Practical consequences: JVM pauses depend on heap size and collector choice and are tuned with flags. CPython has no stop-the-world "full GC" for acyclic garbage, but a large heap makes cycle collections longer. JVM finalisation timing is unpredictable, while CPython's __del__ is usually prompt, which hides bugs until PyPy or a cycle arrives.

See E2 · Java Deep Dive for the JVM side.

Picture it The two mechanisms side by side, and one measured number: how long a full cycle collection takes on a large live heap.

The setup: Hold a million live container objects and time gc.collect() before and after gc.freeze().

q18_gc_cost.py · Python 3.14runs offline
import gc, time

def timed(label):
    t = time.perf_counter()
    n = gc.collect()
    print(f"{label:34}{(time.perf_counter() - t) * 1000:8.1f} ms")

live = [[i] for i in range(1_000_000)]      # a million tracked lists
timed("full collect, 1M live objects")
timed("full collect again")
gc.freeze()
timed("full collect after gc.freeze()")
gc.unfreeze()
del live
timed("full collect after freeing them")
output · Python 3.14runs offline
full collect, 1M live objects         71.9 ms
full collect again                    71.7 ms
full collect after gc.freeze()         0.0 ms
full collect after freeing them        0.7 ms
# measured on the course machine; your numbers will differ

What you see: with a million live lists the full collection takes tens of milliseconds, because it has to look at all of them; after freeze() the same call is nearly instant, and it is also instant once the objects are gone.

Why: the cycle collector's cost grows with the number of tracked objects, not with garbage. The JVM has the opposite cost shape: its pause depends on live data too, but it is hidden by concurrent collectors.

JVM tracing

Mark live objects, drop the rest.

Heap.txtruns offline
roots -> mark reachable
         sweep / compact
new object = bump pointer
free = "someday, by GC"

CPython

Count references, scan cycles.

heap.txtruns offline
every assignment: count +1/-1
count == 0 -> free now
cycles -> separate scanner
no compaction

The shift: The JVM pays in collector threads and pauses; CPython pays a small cost on every assignment and in fragmentation.

Land it I contrast tracing with counting: the JVM scans live data on its own schedule and compacts, CPython frees at zero and scans only for cycles, so latency, fragmentation and resource timing behave differently.

Likely follow-ups
"Which one has lower latency?"

It depends on what you are measuring, and I would want numbers from the real workload. For ordinary request handling, CPython's cost is steady: freeing is done in small pieces as references drop, so there is no big pause for data that has no cycles. A request that allocates and frees a few objects pays that cost in line.

Modern JVM collectors such as ZGC aim for pauses well under a millisecond even on very large heaps, and spend extra CPU on background threads to do it. Check the numbers for your JDK version.

The place where they differ is size. With a huge live object graph, the JVM's concurrent collectors scale better than CPython's cycle collector, which visits every tracked object during a full collection and does it while your code waits. So for a small heap, CPython is predictable. For a very large heap, the JVM has the better tools.

"Why does CPython not compact memory?"

Because objects have fixed addresses that other code relies on. C extensions hold raw pointers to Python objects, and id() exposes the address, so moving an object would break every pointer to it. The C API gives no way to find and update all of them.

The JVM can move objects because it controls every reference. It can pause or coordinate threads, copy live objects together, and fix each reference. After compaction the free space is one contiguous block, and allocation is just bumping a pointer.

CPython pays for that choice with fragmentation. As Q13 shows, a few survivors can pin each pymalloc arena, so RSS stays high after the data is gone. The benefit of fixed addresses is simple C interop, which is a large part of why NumPy and similar libraries exist. It is a design trade, not an oversight.

"How do weak references behave in each?"

The difference is timing, and it changes how you write tests and caches.

  1. CPython: A weak reference dies at the instant the strong count reaches zero. del obj and the entry in a WeakValueDictionary disappears on the next line, unless the object is in a cycle.
  2. Java: A weak reference is cleared at some later collection, when the collector decides. There are also soft references, cleared only under memory pressure and used for caches, and phantom references, used for cleanup actions.
  3. Test impact: In Python, del x; assert key not in cache usually works. In Java you cannot assert at a given moment, because even System.gc() is only a hint.

That makes a WeakValueDictionary simple to test in Python, and a WeakHashMap harder in Java.

"What do Python implementations other than CPython do?"

PyPy uses a tracing, generational collector, so memory is released later and __del__ timing changes. Jython and IronPython use their host virtual machine's collector, which is a JVM or .NET one. Each has the properties of that collector: no immediate freeing, pauses, and no reference counts to query.

Code that relies on CPython's immediate freeing breaks on them. A common example is open(path).read() in a loop, where the file is closed only because the temporary object dies at once. On PyPy, thousands of files may stay open until the collector runs, and you hit the operating system's file limit.

The fix is the one the chapter keeps repeating: use with for files, locks and connections, so cleanup does not depend on who is running your code. I would also avoid sys.getrefcount and __del__ in portable libraries. If your service only ever runs on CPython, this is a code-hygiene argument, not an emergency.

Q19 · Scenario. "A pipeline creates 50 million small objects and runs out of memory. How do you cut memory use?"

Reveal answer

Strong answer Start with the arithmetic. A tiny Python object is not tiny: an int is 28 bytes, a float 24 bytes, a short str about 50, a 3-item tuple 72, and an instance of a normal class with three attributes 48 bytes plus up to about 300 for its __dict__ (recent versions can keep attributes inline and build the dict only when asked, so measure, as the demo does). Fifty million of them at 100 bytes is 5 GB.

Then cut in this order. First, do not hold them all. Stream: read, transform and write one batch at a time with generators (Q52). Second, make each one smaller: __slots__ or a dataclass(slots=True), tuples or NamedTuple for fixed shapes, and shared strings for repeated values. Third, change representation: store numbers in columns, array.array, NumPy, or Arrow, where one million numbers cost 8 MB, not 40 MB.

Last, prove it. Measure with tracemalloc before and after on a million-record sample and multiply; do not guess from getsizeof (Q14).

Picture it What one object costs, and what a million numbers cost in a list versus a compact array.

The setup: Print the size of common small objects, then build one million integers both ways.

q19_object_costs.py · Python 3.14runs offline
import sys, array, tracemalloc

class Plain:
    def __init__(self):
        self.a, self.b, self.c = 1, 2, 3
class Slotted:
    __slots__ = ("a", "b", "c")
    def __init__(self):
        self.a, self.b, self.c = 1, 2, 3

p, s = Plain(), Slotted()
rows = [("int 1000", 1000), ("float", 1.5), ("str 'abcdefg'", "abcdefg"),
        ("tuple of 3", (1, 2, 3)), ("list of 3", [1, 2, 3]), ("dict of 3", {"a": 1, "b": 2, "c": 3}),
        ("Plain instance", p), ("  ...its __dict__", p.__dict__), ("Slotted instance", s)]
for name, obj in rows:
    print(f"{name:20}{sys.getsizeof(obj):6} bytes")

tracemalloc.start()
xs = [i * 1000 for i in range(1_000_000)]
list_mb = tracemalloc.get_traced_memory()[0] / 1e6
del xs
tracemalloc.reset_peak()
ys = array.array("q", (i * 1000 for i in range(1_000_000)))
arr_mb = tracemalloc.get_traced_memory()[0] / 1e6
print(f"1M ints in a list        : {list_mb:5.1f} MB")
print(f"1M ints in array('q')    : {arr_mb:5.1f} MB")
output · Python 3.14runs offline
int 1000                28 bytes
float                   24 bytes
str 'abcdefg'           48 bytes
tuple of 3              72 bytes
list of 3               88 bytes
dict of 3              184 bytes
Plain instance          48 bytes
  ...its __dict__      296 bytes
Slotted instance        56 bytes
1M ints in a list        :  40.4 MB
1M ints in array('q')    :   8.2 MB

What you see: even an int is 28 bytes, an instance with __dict__ costs the instance plus its dict, and a million integers cost about 40 MB in a list but 8 MB in a compact array.

Why: every Python object has a header (type pointer and reference count), and a list adds a pointer to each; an array stores raw 8-byte numbers with no per-item object.

Many objects

One heap object per record.

many.pyruns offline
rows = [Row(i) for i in range(N)]
# N x (object + __dict__)

Compact or streamed

No per-record objects.

compact.pyruns offline
prices = array("d", source)   # columns
for row in stream(source):    # or stream
    handle(row)

The shift: Stop paying per-object overhead: stream the data or store it as columns.

Land it I do the arithmetic per object, stream where possible, shrink what must be held with slots, tuples or columns, and prove the saving with a tracemalloc run on a sample.

Likely follow-ups
"How do I stream when the next step needs all the data?"

Ask whether it truly does, and if so, move the work to disk.

  1. Aggregations need only running state: Sum, count, max, min and group counts keep one small value per group. A collections.Counter or a dict of totals can read a stream of 50 million records and stay small.
  2. Sorting works in chunks: Sort a chunk that fits in memory, write it to a temporary file, repeat, then combine the sorted files with heapq.merge, which reads one item from each at a time. This is an external sort.
  3. Joins and group-bys use a query engine: If it really needs everything at once, put the data in SQLite or DuckDB, or Parquet files, and let the engine work on disk.

I would first try the streaming version, because it is usually shorter than people expect. A sketch of a running aggregate:

running aggregate (snippet)runs offline
from collections import Counter

def count_by_status(records):
    totals = Counter()
    for rec in records:          # one record in memory at a time
        totals[rec.status] += 1
    return totals
"When do I pick NumPy or pandas?"

When the data is numeric and tabular and the operations apply to whole columns. A NumPy array of 50 million float64 values is 50,000,000 x 8 bytes, which is 400 MB, with no per-item object. The same numbers as a Python list of floats cost about 8 bytes for the pointer plus 24 for each float object, about 1.6 GB.

worked exampleruns offline
list of floats : 50,000,000 x (8 pointer + 24 object) = 1,600 MB
numpy float64  : 50,000,000 x 8                       =   400 MB
array.array    : 50,000,000 x 8                       =   400 MB

The operations run in C, which is usually much faster than a Python loop. I pick array.array when I need only compact storage and no dependencies, and NumPy when I also need maths on the data. The cost is a new dependency and a different style: whole-column operations instead of loops, and real trouble for mixed-type records.

For mixed columns with names, pandas or Polars is the next step.

"What does a typical order of wins look like?"

I do not trust a typical percentage, so I measure each change on a sample from the real data. The ordering I try is by effort and risk, not by assumed savings.

Slots is a one-line change and the measured effect is clear: on 3.14, one million small instances took about 104.5 MB without slots and 64.4 MB with them, a saving of roughly 38 % (Q33). Streaming is a rewrite of control flow, but it can remove most of the peak, because only one batch is ever alive. Columns remove the per-item object, so numeric data can fall by a large factor, as the 1.6 GB versus 400 MB comparison under the NumPy question shows.

The order I choose: stream first if the shape allows it, then slots or tuples for what must stay, then columns for numeric fields. After each step I rerun the sample and write the new bytes per record next to the old one.

"What about the garbage collector at 50 million objects?"

Every full cycle scan visits all tracked containers, so pauses grow with the object count. At 50 million tracked objects, one generation-2 collection can take long enough to show up in tail latency.

Tuples and dicts that contain only numbers and strings are untracked after the first collection that examines them, which is one reason tuples help. Instances of classes are tracked, and so are lists. A million plain-class instances therefore mean a million entries for the collector, while a million rows in a NumPy array mean one.

Q17 covers gc.freeze and thresholds. My order of preference is: reduce the count of container objects first, because it saves memory and collector time together, then freeze data that never changes, then consider raising thresholds. Disabling the collector is a last resort, and only if the code creates no cycles.

Q20 · Design. "You are reviewing code that keeps 10 million records as dicts. What do you change, and how do you prove the win?"

Reveal answer

Strong answer First I write down the shape: how many fields, which types, whether keys are fixed, whether the data is read-only after loading. Records with fixed keys are objects pretending to be dicts, and a dict per record repeats the key table for every one.

Options, cheapest change first. A dataclass with slots=True keeps readable attribute access and removes the per-record dict, usually about half the memory or better. A tuple or NamedTuple is smaller still and immutable. Columns (array.array or NumPy per field) are smallest for numeric fields, but change how the code is written. A database file (SQLite or DuckDB) removes the memory limit altogether if you need queries, not loops.

To prove it, I use one script with a representative sample (one million records, not ten), build each variant, record tracemalloc memory per record, and time the operation the service really performs (a scan, a lookup by id). I multiply by ten for the estimate, then confirm in a staging run and compare RSS. I accept a change only if memory and time are both known.

Picture it One million records in four shapes, measured.

The setup: Records of id, price, quantity and SKU, built as dicts, slotted dataclasses, tuples and columns.

q20_record_shapes.py · Python 3.14runs offline
import tracemalloc, array
from dataclasses import dataclass

N = 1_000_000
SKUS = [f"SKU-{k}" for k in range(1000)]          # shared strings, as a real loader would intern

@dataclass(slots=True)
class Rec:
    id: int
    price: float
    qty: int
    sku: str

def as_dicts():
    return [{"id": i, "price": i * 0.5, "qty": i % 7, "sku": SKUS[i % 1000]} for i in range(N)]
def as_slots():
    return [Rec(i, i * 0.5, i % 7, SKUS[i % 1000]) for i in range(N)]
def as_tuples():
    return [(i, i * 0.5, i % 7, SKUS[i % 1000]) for i in range(N)]
def as_columns():
    return (array.array("q", range(N)), array.array("d", (i * 0.5 for i in range(N))),
            array.array("b", (i % 7 for i in range(N))), array.array("H", (i % 1000 for i in range(N))))

for label, build in (("list of dicts", as_dicts), ("list of slotted dataclasses", as_slots),
                     ("list of tuples", as_tuples), ("columns (array.array)", as_columns)):
    tracemalloc.start()
    data = build()
    cur, _ = tracemalloc.get_traced_memory()
    tracemalloc.stop()
    print(f"{label:30}{cur / 1e6:7.0f} MB  {cur / N:6.0f} bytes/record")
    del data
output · Python 3.14runs offline
list of dicts                     248 MB     248 bytes/record
list of slotted dataclasses       128 MB     128 bytes/record
list of tuples                    144 MB     144 bytes/record
columns (array.array)              19 MB      19 bytes/record
# measured on the course machine; your numbers will differ

What you see: dicts are the largest by far, slotted dataclasses and tuples cut memory to roughly half of the dict version, and columns shrink it to under a tenth.

Why: a dict repeats a hash table per record; slots and tuples store only the values, and columns store raw numbers without per-record objects.

Land it I measure per-record bytes on a sample for dicts, slots, tuples and columns, choose the smallest shape that keeps the code readable, and confirm the estimate with an RSS check on the real load.

Likely follow-ups
"Why not go straight to NumPy or pandas?"

If the work is vectorisable (sums, filters and group-bys on numeric columns), they are the right end state, and I would go there. If the code is full of per-record branching and business rules written in Python, rewriting it as array operations is a bigger change than the memory problem justifies, and it can hide the rules.

There is also the dependency and team cost. NumPy and pandas bring a large install, a new vocabulary, and surprises around types, such as integers turning into floats when a missing value appears.

My sequence: start with a slotted dataclass, which keeps the code readable and usually saves about half the memory or better. Measure. Move to columns when profiling shows that the loop, not the memory, is the problem, or when the data is purely numeric. A low-risk first step lets you ship a fix this week and still keep the option of a rewrite.

"How do I keep the code readable with columns?"

Hide the representation behind a small class. The storage is columns (array.array or NumPy per field), and the class has __getitem__ returning a lightweight view, or an __iter__ that yields row objects on demand. Callers see rows. Memory sees columns.

column store (snippet)runs offline
from array import array

class Orders:
    def __init__(self):
        self.ids = array("q")
        self.totals = array("d")

    def add(self, order_id, total):
        self.ids.append(order_id)
        self.totals.append(total)

    def __getitem__(self, i):
        return (self.ids[i], self.totals[i])

Keep the conversion at the boundary: load straight into the columns, and convert only the few rows you display or send into dataclasses. Never build 10 million row objects just to look at them, because that is the memory problem coming back through a side door.

Ten million orders in this layout cost 10,000,000 x (8 + 8) bytes, which is 160 MB, with no per-row object. The price is that the class must provide every operation callers need, so I add methods as real needs appear.

"What if the records must be mutated?"

Slotted dataclasses and arrays are mutable, and tuples are not, so mutation rules out tuples. If updates are frequent and the set is large, I would consider a database, because it handles persistence, indexes and concurrent updates, and a list of objects does none of these.

Think about what the updates look like. Changing a field on one record is cheap in a slotted object and in an array. Inserting or deleting in the middle of a list is O(n). Finding a record by id needs a dict or an index, which adds memory of its own: a dict of 10 million entries has a large table.

So the real question is whether the whole set needs to live in memory at all (Q19 on streaming). If it is a working set that is read and updated in place, SQLite with an index on the key often beats a clever in-memory structure, and it removes the limit.

"How do I prove the win to a skeptical reviewer?"

I attach three things to the pull request: the script, its output table, and an RSS graph from staging before and after. The script is the same for every variant and runs on a sample of one million, so anyone can rerun it. If a number surprises me, I rerun it with a different sample before I defend it.

The table has one row per variant (dict, slotted dataclass, tuple, columns) with bytes per record, total estimated for 10 million, and the time for the operation the service really does, such as a scan or a lookup by id. A change that saves memory but doubles the scan time is a trade the reviewer should see.

I also run the existing tests and add one new test that asserts that the new type behaves like the old one for the operations that matter. That protects against the usual regression in this kind of change: a type that is smaller but misses a method the code used.

Drill · Special methods and protocols

These questions test whether you know that Python syntax is a set of calls to special methods looked up on the type, so you can predict what len, +, for, with and if do to your own classes.

Q21. "What actually happens when you call len(x) or evaluate x + y?"

Reveal answer

Strong answer Both are shorthand for calls to special methods (also called dunder methods, for double underscore). len(x) runs type(x).__len__(x). x + y runs type(x).__add__(x, y).

The important word is type. Python looks the method up on the object's class, not on the instance. Putting a function on one instance, x.__len__ = lambda: 99, has no effect on len(x). This lookup path is quick and lets the interpreter skip per-instance dictionaries for operators.

For x + y there is a fallback chain. First type(x).__add__(x, y). If that returns the special value NotImplemented (or does not exist), Python tries the reflected method type(y).__radd__(y, x). If both decline, it raises TypeError: unsupported operand type(s). A method must return NotImplemented, never raise it, so that the other side gets its turn.

That is the whole mechanism. The language has no operator overloading as such; there is a fixed table of names that syntax calls.

Picture it The calls a class receives, and an instance-level override that is ignored.

The setup: A Basket class with __len__ and __add__, a plain object with only __radd__, and an addition that nobody supports.

q21_special_methods.py · Python 3.14runs offline
class Basket:
    def __init__(self, items):
        self.items = items
    def __len__(self):
        print("  Basket.__len__ called")
        return len(self.items)
    def __add__(self, other):
        print("  Basket.__add__ called")
        if not isinstance(other, Basket):
            return NotImplemented           # decline, do not raise
        return Basket(self.items + other.items)

b = Basket([1, 2, 3])
print("len(b) =", len(b))

b.__len__ = lambda: 99                      # ❌ TRAP: instance attribute is ignored by len()
print("after patching the instance: len(b) =", len(b), "| b.__len__() =", b.__len__())

print("b + b ->", (b + b).items)

class Weird:
    def __radd__(self, left):
        print("  Weird.__radd__ got a", type(left).__name__)
        return "handled by the right-hand side"

print("b + Weird() ->", b + Weird())
try:
    b + 5
except TypeError as e:
    print("b + 5 ->", e)
output · Python 3.14runs offline
  Basket.__len__ called
len(b) = 3
  Basket.__len__ called
after patching the instance: len(b) = 3 | b.__len__() = 99
  Basket.__add__ called
b + b -> [1, 2, 3, 1, 2, 3]
  Basket.__add__ called
  Weird.__radd__ got a Basket
b + Weird() -> handled by the right-hand side
  Basket.__add__ called
b + 5 -> unsupported operand type(s) for +: 'Basket' and 'int'

What you see: len(b) calls the class method even after the instance attribute is set, while b.__len__() (a normal attribute lookup) finds the instance's version. b + Weird() first calls Basket.__add__, gets NotImplemented, then calls Weird.__radd__.

Why: operators ask the type, which is also why they are fast and why they cannot be monkey-patched per object.

Java

No operators for your classes.

Basket.javaruns offline
int n = basket.size();
Basket c = a.plus(b);
// operators are for primitives
// and String only

Python

Syntax calls dunder methods.

basket.pyruns offline
n = len(basket)     # __len__
c = a + b           # __add__
# any class can opt in

The shift: In Python the syntax is the interface: implement the special method and your class works with the built-in function or operator.

Land it I say len(x) and x + y call type(x).__len__ and type(x).__add__, with __radd__ as the fallback when the left side returns NotImplemented.

Likely follow-ups
"Why return NotImplemented instead of raising TypeError?"

Because returning NotImplemented tells Python "I do not know how to handle this partner, ask the other operand". If you raised TypeError yourself, the class on the right, which might know how to add you, would never get a turn. The run uses two classes, where only the right-hand one knows the conversion.

q21_notimpl.py (output)runs offline
4.048
TypeError: unsupported operand type(s) for +: 'Meters' and 'str'

Meters(1) + Feet(10): Meters.__add__ sees a partner it does not understand and returns NotImplemented. Python then calls Feet.__radd__, which converts and returns 4.048 meters. With "x" both sides decline, and Python raises the TypeError itself, with a message naming both types.

NotImplemented is a singleton value, not an exception, and the comparison methods __eq__ and __lt__ use it the same way. Returning it is a cooperation rule between classes.

"How does len() check the result?"

len insists on a non-negative integer from __len__. Anything else is an error, and the run shows the exact messages.

q21_len.py (output)runs offline
3
ValueError: __len__() should return >= 0
TypeError: 'float' object cannot be interpreted as an integer

The first call is fine, the second returns -1 and raises ValueError, and the third returns 2.5 and raises TypeError. For built-in types the call is a fast path in C, so len([...]) does not go through a Python-level method lookup.

That is why the built-in function exists at all. It is one consistent entry point with validation, instead of every class inventing .length(), .size() or .count(). It also lets truthiness work: an object with no __bool__ is falsy when __len__ returns 0, which is why if items: works for any container.

"What are the in-place operators?"

The in-place operators have their own special methods, and the fallback is what trips people up.

  1. The order: x += y tries type(x).__iadd__(x, y) first. If the class does not define it, or it returns NotImplemented, Python falls back to x = x + y, which uses __add__ and then __radd__.
  2. Who defines it: Lists define __iadd__, which mutates and returns the same list. Strings, ints and tuples do not, so += on them rebinds the name to a new object. That is the difference Q6 trips over.
  3. The contract: __iadd__ must return the object that the name should be bound to, almost always self. If you forget the return, the name becomes None.

I define __iadd__ only if the class can really mutate in place and callers expect it, such as a collection. For value objects I leave it out and let += build a new object, which keeps them immutable.

"Which special methods should a senior know by heart?"

Construction and representation: __new__, __init__, __repr__, __str__. Comparison and hashing: __eq__, __lt__, __hash__. Containers: __len__, __getitem__, __contains__, __iter__. Callables and resources: __call__, __enter__, __exit__. Attribute access: __getattr__, __getattribute__, __set__ and the descriptor family.

I group them this way because the groups map to behaviour. If the interviewer asks what makes something work in a for loop, I answer __iter__; in with, the enter/exit pair; as a dict key, the pair __eq__ and __hash__.

The rule of thumb is to implement the smallest protocol that makes your class useful and let the standard library supply the rest. functools.total_ordering builds the other comparisons from __eq__ and one ordering method, and the collections.abc mixins give a full Mapping or Sequence from a few methods. Knowing the list is less valuable than knowing why len(x) looks the method up on the type, not the instance.

Q22 · Scenario. "After adding __eq__ to a class, putting its instances in a set raises TypeError. Why?"

Reveal answer

Strong answer When you define __eq__ in a class body and do not define __hash__, Python sets __hash__ to None for that class. The class is then deliberately unhashable, and a set or dict key asks for the hash and gets TypeError: unhashable type.

Python does this to protect you from a broken contract. The rule is: objects that compare equal must have equal hashes. A new __eq__ says that two different instances can now be equal; the inherited identity-based hash would give them different hashes, and a set would then contain "equal" duplicates and fail lookups. Removing the hash is safer than keeping a wrong one.

The fix depends on meaning. If instances are values (a price rule defined by its fields), make it immutable and hash the same fields you compare: @dataclass(frozen=True) writes both methods. If instances are mutable entities, do not hash them by value; leave them unhashable or hash by a stable id field.

Never hash on a field that can change after the object is in a set or dict, because the object ends up in the wrong bucket.

Picture it The crash, the hash that disappeared, and the fixes.

The setup: A PriceRule gets __eq__ for tests, then goes into a set of rules.

q22_eq_hash.py · Python 3.14runs offline
from dataclasses import dataclass

class PriceRule:
    def __init__(self, code, pct):
        self.code, self.pct = code, pct
    def __eq__(self, other):                      # ❌ TRAP: hash silently disabled
        return (self.code, self.pct) == (other.code, other.pct)

print("__hash__ is:", PriceRule.__hash__)
try:
    {PriceRule("FIRST50", 50)}
except TypeError as e:
    print("set ->", e)

@dataclass(frozen=True)                           # ✅ eq and hash from the same fields
class FrozenRule:
    code: str
    pct: int

rules = {FrozenRule("FIRST50", 50), FrozenRule("FIRST50", 50), FrozenRule("VIP10", 10)}
print("set of frozen rules:", len(rules), "unique")

class LooseHash:
    def __init__(self, code):
        self.code = code
    def __eq__(self, other):
        return self.code == other.code
    def __hash__(self):                           # ❌ TRAP: hash on a mutable field
        return hash(self.code)

r = LooseHash("A")
s = {r}
r.code = "B"                                      # mutated after insertion
print("object is in the set:", r in s, "| set still holds", len(s), "element")
output · Python 3.14runs offline
__hash__ is: None
set -> cannot use 'PriceRule' as a set element (unhashable type: 'PriceRule')
set of frozen rules: 2 unique
object is in the set: False | set still holds 1 element

What you see: the first class prints __hash__ is: None and the set raises. The frozen dataclass collapses duplicates correctly. The last class shows the mutation trap: after the field changes, the object is "in" the set yet cannot be found.

Why: a set finds elements by hash. When the hash changes under it, the lookup goes to a different slot.

Java · Spring

Forgetting hashCode is silent.

Rule.javaruns offline
@Override
public boolean equals(Object o) { ... }
// no hashCode() override:
// HashSet misbehaves quietly

Python

Python makes the mistake loud.

rule.pyruns offline
def __eq__(self, other): ...
# __hash__ is now None:
# set([...]) -> TypeError

The shift: Java lets you break the equals/hashCode contract and fail silently; Python removes the hash and fails at once. See the eq/hash idiom.

Land it I explain that __eq__ without __hash__ sets the hash to None to protect the contract, and I fix it with a frozen dataclass or a hash over the same immutable fields.

Likely follow-ups
"Why not keep the default identity hash?"

Because it would break the rule that equal objects have equal hashes. Take two rules with the same code and the same percentage. After you add __eq__, they are equal. With the inherited identity hash, they would still have different hashes, since the hash comes from the address.

The consequences are bad and quiet. A set could hold both rules, even though they are equal. rule in rules could say False for a rule equal to one inside, because the lookup probes the wrong bucket. A dict could hold duplicate keys.

Python removes the hash to stop that, and it makes you decide what the hash should be. The failure is loud (TypeError: unhashable type) instead of a wrong answer a month later. I count that as a good trade, because loud errors are easy to find.

"How do I define __hash__ by hand?"

Hash a tuple of exactly the fields that __eq__ compares: return hash((self.code, self.pct)). Hashing a tuple mixes the hashes of its parts, so you do not need to invent a mixing formula, and a bad hand-made formula such as adding the two hashes causes collisions.

rule class (snippet)runs offline
class PriceRule:
    def __init__(self, code, pct):
        self.code, self.pct = code, pct

    def __eq__(self, other):
        if not isinstance(other, PriceRule):
            return NotImplemented
        return (self.code, self.pct) == (other.code, other.pct)

    def __hash__(self):
        return hash((self.code, self.pct))

The fields must be immutable in practice. If a field can change after the object is in a set, the stored hash no longer matches and the object is lost: rule in rules looks in the old bucket and says False. If you cannot freeze them, do not define a value hash. The object is an entity, and it should be identified by an id or by identity. A frozen dataclass writes all of this for you.

"What does @dataclass(eq=True) do for hashing?"

The hash depends on the flags. With eq=True (the default) and no frozen, the dataclass sets __hash__ to None, the same behaviour as in the question. With frozen=True, eq=True it generates a __hash__ from the fields. unsafe_hash=True forces one for a mutable class, and the name is a warning. The run shows it.

q22_hash.py (output)runs offline
None
True 1
None

The first line is A.__hash__ for a plain dataclass: None. The second shows that two equal frozen instances hash equally and a set keeps one of them. The third is a hand-written class that defined __eq__ only.

So frozen=True is the answer whenever instances are values. I use unsafe_hash never, and when someone proposes it I ask which field is going to change.

"Does this affect subclasses?"

Yes. A subclass that defines __eq__ loses the parent's __hash__ in exactly the same way, because the rule applies to every class body. A subclass that defines neither keeps both.

If you want to keep the parent's hash, assign it explicitly in the subclass body: __hash__ = Parent.__hash__. Then make sure the new equality still agrees with the inherited hash. For example, if the subclass adds a field to equality but the inherited hash ignores it, you are still legal, since equal objects still hash equally, but you will get more collisions.

Equality across types is where most real bugs hide. Decide whether Rule("A") == "A", and then make the hash agree. My default is for __eq__ to return NotImplemented for any other type, which makes instances of different classes unequal, and keeps the hash question simple.

Q23. "Iterable versus iterator — and why does looping over a generator a second time produce nothing?"

Reveal answer

Strong answer An iterable is anything you can loop over: it has __iter__, which returns a fresh iterator each time. Lists, strings, dicts and files are iterables. An iterator is the object that does the walking: it has __next__, which returns the next item or raises StopIteration, and its own __iter__ returns itself.

A list is iterable but not an iterator. Each for loop calls iter(my_list) and gets a new iterator with its own position, so you can loop over a list many times.

A generator is an iterator. It is its own iterable, with one position that only moves forward. After the first loop runs to the end, the generator is exhausted. A second loop calls iter(gen), receives the same exhausted generator, and __next__ raises StopIteration straight away, so the body never runs and no error appears.

The practical rule: if you need to loop twice, store the results (list(gen)) or create a new generator each time. Beware functions that quietly accept one-shot iterators and process them twice.

Picture it The same data looped twice as a list and as a generator, and what for really does.

The setup: Loop twice over a list and over a generator, then replace the for with its while equivalent.

q23_iterators.py · Python 3.14runs offline
def numbers():
    yield 1
    yield 2

data = [1, 2]
gen = numbers()
for label, source in (("list", data), ("generator", gen)):
    first = [x for x in source]
    second = [x for x in source]
    print(f"{label:10} first pass: {first}   second pass: {second}")

print("list is its own iterator?     ", iter(data) is data)
print("generator is its own iterator?", iter(gen) is gen)

print("--- what `for x in data:` does")
it = iter(data)                 # 1. ask the iterable for an iterator
while True:
    try:
        x = next(it)            # 2. pull until StopIteration
    except StopIteration:
        break
    print("  body ran with", x)
output · Python 3.14runs offline
list       first pass: [1, 2]   second pass: [1, 2]
generator  first pass: [1, 2]   second pass: []
list is its own iterator?      False
generator is its own iterator? True
--- what `for x in data:` does
  body ran with 1
  body ran with 2

What you see: the list gives [1, 2] twice; the generator gives [1, 2] and then []. The while loop prints the same items as a for would.

Why: iter(list) builds a new walker each time; iter(generator) returns the same, already finished, one.

Reusable

Iterable: new walker per loop.

reuse.pyruns offline
rows = [1, 2, 3]
sum(rows)   # 6
sum(rows)   # 6

One-shot

Iterator: one walk only.

once.pyruns offline
rows = (x for x in [1, 2, 3])
sum(rows)   # 6
sum(rows)   # 0  <- silent

The shift: A generator is a stream, not a collection; looping twice needs a new stream.

Land it I distinguish iterables (new iterator per loop) from iterators (one forward pass, __next__, exhausted forever), and I materialise with list() when I need two passes.

Likely follow-ups
"How do I make my own class iterable?"

Two ways. The usual one is to define __iter__ so that it returns a new iterator each time, and the easiest way to do that is to write it as a generator with yield. The older way is to define __getitem__ for integer indexes starting at 0, and Python falls back to calling it until IndexError.

iterable class (snippet)runs offline
class Basket:
    def __init__(self, items):
        self._items = list(items)

    def __iter__(self):
        yield from self._items

Each call to iter(basket) runs __iter__ again and returns a fresh generator, so the basket can be looped over many times, and several loops can be in progress at once. That is the property that separates an iterable from an iterator.

I avoid returning self from __iter__ on a container: that would make it a one-shot iterator and bring the Q23 bug in through the class itself.

"How can I detect a one-shot iterator in an API?"

The test is iter(x) is x. For an iterator it is true, because an iterator returns itself. For a list it is false, because each call makes a new iterator. The run shows both, and shows what the bug looks like in a total.

q23_iter.py (output)runs offline
False True
3 0

The first line says the list is not its own iterator and the generator is. The second shows sum run twice on the same generator: 3 the first time, 0 the second.

A defensive function that needs two passes can check iter(x) is x and call list(x) first, or its signature can say what it needs. In type hints, Iterable[T] promises one pass; Sequence[T] or Collection[T] promises repeatable iteration and a length. Choosing the right hint documents the contract.

"Why does for not raise when the generator is already empty?"

Because "no items" is a valid outcome of looping, and the protocol makes no difference between empty and finished.

  1. How it ends: StopIteration is how an iterator says "I am finished". The for loop catches it and exits normally, so there is nothing to report.
  2. What an exhausted generator is: It is an iterator whose next call raises StopIteration at once. To the loop, that is the same as an empty sequence.
  3. Why the bug is silent: Totals come out as 0, reports have no rows, and a test that only checks "does not crash" passes.

The defence is a test that asserts a nonzero result, and code that makes the data repeatable on purpose: store it with list(), or build a new generator for each pass. In a pipeline I name generator variables clearly, such as rows_iter, so a second use reads as suspicious.

"What happens inside list(gen) and sum(gen)?"

Each calls iter() on its argument, then calls next() repeatedly until StopIteration, doing its own work as items arrive. sum(gen) keeps one running total, so it uses little memory. list(gen) stores every item, so it uses memory in proportion to the length.

Everything built on iteration follows the same protocol: sorted, max, tuple, set, zip, enumerate and the in operator on iterables. That is why they all accept generators, files and your own iterables without caring about the type.

The practical effect is on memory: sum(x * x for x in range(10_000_000)) never holds the ten million numbers, while sum([x * x for x in range(10_000_000)]) builds the whole list first. Note also that sorted and list must consume everything before returning, so on an endless generator they never finish, while zip and enumerate stay lazy.

Q24. "How does a with statement work, and how can __exit__ swallow an exception?"

Reveal answer

The real test Whether you can describe with as a try/finally with a protocol, and know that returning a truthy value from __exit__ suppresses the exception.

Strong answer with A() as x: body calls A().__enter__() and binds its return value to x. It then runs the body inside a try. When the body ends, normally or by exception, Python calls __exit__(exc_type, exc, tb). On a normal finish those three are None.

If the body raised, __exit__ receives the exception. If it returns a truthy value, Python treats the exception as handled and execution continues after the with block. If it returns None or False, the exception continues to propagate after __exit__ finishes. If __exit__ itself raises, that new exception replaces the old.

So a context manager is try/finally plus the option to suppress, packaged as a reusable object. Typical uses: close a file, release a lock, commit or roll back a transaction, restore a setting, time a block.

Swallowing should be narrow and visible: contextlib.suppress(FileNotFoundError) swallows exactly one named exception type. A custom __exit__ that returns True unconditionally hides every bug inside the block.

Picture it A context manager that logs and suppresses, and the long-hand version of with.

The setup: A Guard class with a configurable __exit__, then the same flow without with.

q24_with_exit.py · Python 3.14runs offline
class Guard:
    def __init__(self, swallow):
        self.swallow = swallow
    def __enter__(self):
        print("  enter")
        return self
    def __exit__(self, exc_type, exc, tb):
        print("  exit with:", exc_type.__name__ if exc_type else None)
        return self.swallow                    # truthy = suppress

print("swallowing guard:")
with Guard(True):
    raise ValueError("lost")
print("  program continues after the with block")

print("non-swallowing guard:")
try:
    with Guard(False):
        raise ValueError("kept")
except ValueError as e:
    print("  caught outside:", e)

print("the same, without `with`:")
mgr = Guard(True)
mgr.__enter__()
try:
    raise ValueError("lost again")
except BaseException as e:
    if not mgr.__exit__(type(e), e, e.__traceback__):
        raise
else:
    mgr.__exit__(None, None, None)
print("  done")
output · Python 3.14runs offline
swallowing guard:
  enter
  exit with: ValueError
  program continues after the with block
non-swallowing guard:
  enter
  exit with: ValueError
  caught outside: kept
the same, without `with`:
  enter
  exit with: ValueError
  done

What you see: with True the ValueError vanishes and the program continues; with False the same error reaches the outer except. The long-hand version behaves identically.

Why: with is syntax for "call enter, run the body in a try, always call exit, and let exit decide whether the error survives".

Java · Spring

try-with-resources.

Res.javaruns offline
try (var conn = open()) {
  conn.query();
}   // close() always runs
// suppression: addSuppressed

Python

with and __exit__.

res.pyruns offline
with open_conn() as conn:
    conn.query()
# __exit__ always runs;
# returning True hides errors

The shift: Both guarantee cleanup; Python's __exit__ additionally sees the exception and may decide to swallow it. See the context-manager idiom.

Land it I say with calls __enter__, runs the body in a try, always calls __exit__ with the exception details, and a truthy return swallows the error, so I swallow only specific exceptions.

Likely follow-ups
"What if __enter__ raises?"

Then __exit__ is not called, because the context was never entered. That is the reason acquisition belongs in __enter__ and release in __exit__, and the reason a half-acquired resource must clean itself up before it raises.

With several managers in one statement, the managers entered before the failing one are exited. The run uses three managers, where the second fails on entry.

q24_enter.py (output)runs offline
enter a
enter b
exit a
raised b

a was entered, so its __exit__ runs. b failed in __enter__, so it does not exit. c was never entered, and the body never ran. Python handles this nesting for you, which is one reason with a, b: is safer than hand-written nested try blocks.

"Does with give the block a new scope?"

No. Names bound inside the block, including the as name, stay visible after it. Python scopes are for functions, classes and modules, not for blocks, so with, for, if and while all share the surrounding scope.

This surprises Java engineers, where a variable declared inside a block disappears at the closing brace. In Python, with open(p) as f: data = f.read() leaves both f and data usable below. f is closed but still a name.

It is also a source of bugs. A name first assigned inside a block that did not run, for example inside an if, raises UnboundLocalError or NameError when used later. And a loop variable leaks: after for i in range(3), i is 2. My habit is to give a name a value before the block, or to keep the block small and return what is needed.

"How do async context managers differ?"

The shape is the same, with coroutines instead of plain methods, so acquiring and releasing can wait for I/O.

  1. The methods: async with calls __aenter__ and __aexit__, which are async def methods and are awaited. A synchronous with on an async manager is an error.
  2. Where I use it: Connection pools, database transactions, locks such as asyncio.Lock, and task groups (asyncio.TaskGroup), anywhere that release needs a network round trip or a wait.
  3. The suppression rule: It is unchanged: a truthy return value from __aexit__ swallows the exception.

One more difference: an __aexit__ must not block the event loop. If it needs a blocking call, I run it in a thread with asyncio.to_thread. For simple cases @contextlib.asynccontextmanager gives the same short form as the sync version.

"Which standard-library context managers are worth knowing?"

The ones I reach for: open for files, threading.Lock for locking, tempfile.TemporaryDirectory for scratch space, decimal.localcontext for scoped precision, and contextlib.suppress for one named exception. Also contextlib.redirect_stdout for capturing output, contextlib.ExitStack for a variable number of resources, and unittest.mock.patch in tests. Most database drivers make connections and transactions context managers too.

In tests, pytest.raises is a context manager that swallows exactly the expected exception, and fails the test if none arrives. That is the same idea as suppress, with a check attached.

What these share is a pair of actions that must be balanced: acquire and release, begin and commit, change and restore. Whenever I see that pair written by hand with a try/finally, I ask whether a context manager would make the pairing impossible to forget.

Q25. "Write the same context manager twice: as a class and with contextlib."

Reveal answer

Strong answer I will write a timer that reports how long its block took. The class version implements __enter__ and __exit__. The generator version uses @contextlib.contextmanager: everything before yield is the enter part, the yield hands control to the body, and everything after is the exit part.

In the generator version, wrap the yield in try/finally. If the body raises, the exception is thrown into the generator at the yield line, and without finally the cleanup code after it would be skipped.

When to choose which. The decorator form is shorter and reads top to bottom, good for most cases. The class form is better when the manager has state you want to inspect afterwards, when it must be reusable or re-entrant, when you need to control suppression precisely, or when a type name matters.

For several resources, contextlib.ExitStack lets you enter a variable number of managers and closes them all in reverse order, even if one fails midway.

Picture it Two implementations, same behaviour, one extra case with ExitStack.

The setup: Both timers measure a short block; then an ExitStack opens three resources.

q25_two_managers.py · Python 3.14runs offline
import time
from contextlib import contextmanager, ExitStack

class Timer:                                       # class version
    def __enter__(self):
        self.start = time.perf_counter()
        return self
    def __exit__(self, exc_type, exc, tb):
        self.elapsed = time.perf_counter() - self.start
        return False                               # never swallow

@contextmanager
def timer():                                       # generator version
    box = {}
    start = time.perf_counter()
    try:
        yield box
    finally:
        box["elapsed"] = time.perf_counter() - start

with Timer() as t:
    time.sleep(0.05)
with timer() as box:
    time.sleep(0.05)
print(f"class     : {t.elapsed * 1000:.0f} ms")
print(f"generator : {box['elapsed'] * 1000:.0f} ms")

@contextmanager
def resource(name):
    print("  open", name)
    try:
        yield name
    finally:
        print("  close", name)

with ExitStack() as stack:
    for n in ("db", "cache", "queue"):
        stack.enter_context(resource(n))
    print("  working with", n)
output · Python 3.14runs offline
class     : 50 ms
generator : 50 ms
  open db
  open cache
  open queue
  working with queue
  close queue
  close cache
  close db

What you see: both timers print about 50 ms, and ExitStack closes the three resources in reverse order (queue, cache, db) when the block ends.

Why: the decorator turns the generator's two halves into __enter__ and __exit__; ExitStack keeps a list of exit callbacks and runs them last-in, first-out.

Land it I write it as a class when state or precise control matters and with @contextmanager otherwise, with try/finally around the yield, and I use ExitStack for a variable number of resources.

Likely follow-ups
"What happens if I forget try/finally around the yield?"

When the body raises, the exception is thrown into the generator at the yield line. With no finally, the code after the yield never runs, so the cleanup is skipped and the exception then propagates. The run compares a manager without and with finally.

q25_nofinally.py (output)runs offline
open
-> raised
open
close
-> raised

The first manager printed open and never close: the resource leaked. The second, with try/finally, closed correctly.

So the rule is to put release code in finally. If you want to swallow an exception, catch it around the yield and do not re-raise. Both patterns are visible in the code, and neither depends on the reader remembering what happens on error.

"Can a @contextmanager function be reused as a decorator?"

Yes. A manager built with @contextmanager can be applied as a decorator, because the class that wraps the generator inherits from contextlib.ContextDecorator. For a class you write yourself, inherit from ContextDecorator to get the same effect. @timer() then wraps the whole function body in the with.

For decorator use, a fresh generator is created on each call of the decorated function, so each call has its own enter and exit. That is what lets the decorator work for recursive or repeated calls.

The limitation is reuse of one manager object in two with statements. A generator-based manager can be entered only once: the second time the generator has finished, and you get a RuntimeError. If you need a reusable, re-entrant manager, write a class and keep the state per entry. For the decorator case I would check the version's documentation for details such as async functions, which a sync decorator does not wrap properly.

"How do I handle errors during cleanup?"

ExitStack handles it for you. If one exit callback raises, it still runs the remaining ones, and finally raises, with the earlier exception attached as the context. The run registers three callbacks, where the middle one fails.

q25_exiterr.py (output)runs offline
closing c
closing a
raised: close failed

The callbacks run in the reverse order of registration, so c goes first. The failing one raises, and a, registered earlier, still runs. Only after all of them have run does the error reach the caller.

Doing this by hand with nested try/finally is where bugs live: an error in one cleanup can skip the cleanups beneath it. That is why ExitStack exists, and why I reach for it any time the number of resources is decided at run time.

"Is there an async equivalent?"

Yes, and the shape is identical to the synchronous version.

  1. The decorator: @contextlib.asynccontextmanager on an async def with yield and try/finally, used with async with.
  2. Many resources: contextlib.AsyncExitStack is the async twin of ExitStack. You can enter both sync and async managers, and the stack closes everything in reverse order, even if one cleanup fails.
  3. What I use them for: Connection pools, locks, semaphores, transactions, and a task group that must be cancelled and awaited when a block ends.

One difference to remember: cleanup in finally can itself await, so a slow close delays the exit of the block. If cancellation arrives while the cleanup is awaiting, the cleanup may be interrupted, so for critical cleanup I protect it with asyncio.shield or keep it short.

Q26. "__getattr__ versus __getattribute__ — when is each called, and how do you avoid infinite recursion?"

Reveal answer

Strong answer __getattribute__ is called for every attribute access on an instance, obj.anything. Its default implementation does the normal lookup (Q31). __getattr__ is only a fallback: Python calls it after the normal lookup has failed with AttributeError.

So __getattr__ is the safe hook for "if the attribute is missing, compute or delegate it": lazy values, proxies, forwarding to a wrapped object. __getattribute__ is the hook for "intercept everything", used rarely, for proxies and instrumentation, because it runs on every access and slows everything down.

The recursion trap: inside __getattribute__, any access such as self.something calls __getattribute__ again, forever. The fix is to reach the real lookup through object.__getattribute__(self, name) (or super().__getattribute__(name)). In __getattr__ the trap is subtler: if it reads an attribute that does not exist yet, for example self._target before __init__ set it (which happens during copy and pickle), it recurses.

Keep __getattr__ strict: raise AttributeError for names you do not handle, so hasattr and getattr(obj, name, default) keep working.

Picture it The order of calls, and the recursion that ends in RecursionError.

The setup: Three small classes: a fallback, a spy and a broken interceptor.

q26_getattr.py · Python 3.14runs offline
class Lazy:
    def __init__(self):
        self.real = 1
    def __getattr__(self, name):
        print(f"  __getattr__({name!r}) called")
        if name.startswith("_"):
            raise AttributeError(name)       # stay strict for private names
        return f"computed-{name}"

lz = Lazy()
print("lz.real    ->", lz.real)              # normal lookup works, no __getattr__
print("lz.missing ->", lz.missing)            # lookup failed, fallback runs

class Spy:
    x = 10
    def __getattribute__(self, name):
        print(f"  __getattribute__({name!r})")
        return object.__getattribute__(self, name)     # ✅ real lookup, no recursion

print("Spy().x    ->", Spy().x)

class Broken:
    def __getattribute__(self, name):
        return self.__dict__[name]            # ❌ TRAP: self.__dict__ calls us again

try:
    Broken().foo
except RecursionError as e:
    print("Broken().foo -> RecursionError:", str(e)[:35])
output · Python 3.14runs offline
lz.real    -> 1
  __getattr__('missing') called
lz.missing -> computed-missing
  __getattribute__('x')
Spy().x    -> 10
Broken().foo -> RecursionError: maximum recursion depth exceeded

What you see: __getattr__ runs only for missing. __getattribute__ runs for the access to x. The broken version recurses until Python gives up.

Why: __getattribute__ is step zero of every access, and reading self.__dict__ is itself an access.

Runs on every access

__getattribute__

every.pyruns offline
def __getattribute__(self, n):
    log(n)
    return object.__getattribute__(
        self, n)

Runs only on failure

__getattr__

fallback.pyruns offline
def __getattr__(self, n):
    if n.startswith("_"):
        raise AttributeError(n)
    return compute(n)

The shift: Use the fallback hook by default; the every-access hook is for tools, and it must delegate with object.__getattribute__.

Land it I use __getattr__ for missing-attribute fallbacks and keep it strict, and I touch __getattribute__ only for instrumentation, always delegating through object.__getattribute__.

Likely follow-ups
"Why does copy.copy or pickle break a naive proxy?"

Both tools build the object without running __init__. copy.copy makes an empty instance, then asks it for special names such as __setstate__ or __deepcopy__. That empty instance has no _target yet.

Your __getattr__ is called for the missing special name. It reads self._target, which is also missing, so Python calls __getattr__("_target"), which reads self._target again, and so on until RecursionError. Unpickling does the same dance, which is why a proxy that works in a quick test can crash only when it is cached with copy, sent to another process, or stored with pickle.

q26_proxy_copy.pyruns offline
naive : RecursionError
guarded: Guarded 1

The guarded version raises AttributeError at once for any name that starts with an underscore. My rule: __getattr__ must never read an attribute that only __init__ creates, unless it guards that name first.

"Do special methods like len(x) go through __getattr__?"

No. For an implicit call such as len(x), Python looks the method up on the type and skips both __getattribute__ and __getattr__ of the instance. So len(proxy) fails with TypeError: object of type 'Proxy' has no len(), even though writing proxy.__len__() by hand would reach __getattr__ and work.

The reason is speed and predictability. The interpreter calls these operations from fixed slots on the type, with no Python-level search each time. A value stuck in the instance dictionary under the name __len__ is ignored on purpose.

A proxy that must behave like a list needs __len__, __iter__, __getitem__ and __contains__ written on its class, each forwarding to the target. For a long list of methods I generate the forwarders in a loop, or use wrapt. If I need only two or three, I write them by hand.

"What does __setattr__ have to do with it?"

__setattr__ is the write-side twin: it runs for every assignment obj.x = v, including the ones inside __init__. It has the same trap as __getattribute__. Inside it, self.x = v calls __setattr__ again, forever.

The way out is to call the base implementation: super().__setattr__(name, value) or object.__setattr__(self, name, value). That runs the normal rules (a data descriptor first, then the instance dictionary) without re-entering your hook. __delattr__ works the same way for del obj.x.

Frozen dataclasses show the pattern. Their generated __setattr__ raises FrozenInstanceError, and their own __init__ writes the fields with object.__setattr__, the trick Money used in Q10.

I use a __setattr__ hook for read-only objects or change logging. For one validated field I prefer a property, and for many a descriptor (Q32), because one big hook full of if name == branches is hard to read.

"What is the cost of overriding __getattribute__?"

It is large, because every read now runs a Python function. I measured one million reads of o.x on this machine. A plain instance took about 11 ns per read on Python 3.12 and about 12 ns on 3.14. The same class with a __getattribute__ that only forwards to object.__getattribute__ took about 131 ns on 3.12 and about 99 ns on 3.14, roughly ten times slower.

The cause is that the hook is also called for method lookups such as self.method, and for attributes you read inside your own hook. The specialising interpreter (Q63) cannot cache a lookup it has to hand to Python code.

A class used in a hot loop pays this on every line. If you need a computed or validated attribute, use property or a descriptor (Q32), which only intercept the names you choose. I keep __getattribute__ for proxies and tracing tools, where interception is the whole point.

Q27. "How do __bool__ and __len__ decide truthiness, and which bugs does if not value: hide?"

Reveal answer

Strong answer For if x: Python calls x.__bool__() if the class defines it. If not, it calls x.__len__() and treats zero as false. If the class defines neither, the object is always true. A __bool__ must return a real bool; __len__ an integer.

The built-in "falsy" values follow from that: None, False, 0, 0.0, "", [], (), {}, set(), range(0). Everything else is truthy, including "0", "False", [0] and any plain object.

The bug if not value: hides is that it lumps "missing" together with "present but empty or zero". limit = 0, an empty cart, an empty-string coupon and a zero price are all valid values that if not limit: treats as unset. The usual victims are defaults: limit = limit or 10 turns an explicit 0 into 10.

The rule is to test what you mean. is None when you mean "not supplied". len(x) == 0 or plain truthiness when you really mean "empty". Compare with 0 when you mean zero.

Picture it A default that overrides a valid zero, and the order __bool__ then __len__.

The setup: A pricing function and a class defining both methods.

q27_truthiness.py · Python 3.14runs offline
def page_size(limit=None):
    if not limit:                  # ❌ TRAP: 0 is a real answer here
        limit = 10
    return limit

def page_size_fixed(limit=None):
    if limit is None:              # ✅ says exactly what it means
        limit = 10
    return limit

print("limit=0  buggy:", page_size(0), "| fixed:", page_size_fixed(0))
print("falsy:", [v for v in (None, False, 0, 0.0, "", [], (), {}, set(), "0", [0]) if not v])

class Both:
    def __len__(self):
        print("  __len__ asked")
        return 5
    def __bool__(self):
        print("  __bool__ asked")
        return False

class OnlyLen:
    def __len__(self):
        print("  __len__ asked")
        return 0

print("Both ->", bool(Both()))
print("OnlyLen ->", bool(OnlyLen()))
print("plain object ->", bool(object()))
output · Python 3.14runs offline
limit=0  buggy: 10 | fixed: 0
falsy: [None, False, 0, 0.0, '', [], (), {}, set()]
  __bool__ asked
Both -> False
  __len__ asked
OnlyLen -> False
plain object -> True

What you see: limit=0 becomes 10 in the buggy function and stays 0 in the fixed one. The list of falsy values includes the empty containers but not "0" or [0]. __bool__ wins over __len__.

Why: truthiness is a protocol with a lookup order, and plain if x: cannot tell "none" from "zero".

Sloppy

Truthiness as "is it set?"

sloppy.pyruns offline
limit = limit or 10
if not coupon:
    coupon = "NONE"
# 0 and "" are overwritten

Exact

Say what you mean.

exact.pyruns offline
if limit is None:
    limit = 10
if coupon is None:
    coupon = "NONE"

The shift: Use is None for "not supplied" and truthiness only for "is there anything in it?".

Land it I say truthiness is __bool__ then __len__, and I avoid if not value: whenever 0, an empty string or an empty list could be a legitimate value.

Likely follow-ups
"When is if not items: the right test?"

It is the right test when "missing" and "empty" mean the same thing to you, which is common for containers. if not orders: return is short, fast, and the style PEP 8 recommends for sequences. Reading it, everyone knows you mean "nothing to do".

It goes wrong when a parameter can be None (not supplied) or an empty list (supplied, deliberately empty) and the two must behave differently. For example, a filter list of None may mean "no filter", while [] may mean "match nothing". The not test merges them, so one of the two cases is silently wrong.

My habit is simple. For "did the caller give me something?", I write if items is None. For "is there anything in it?", I write if not items or if len(items) == 0. And if neither fits, I write the comparison I mean, such as if limit == 0.

"What goes wrong with NumPy arrays and pandas objects?"

A NumPy array with more than one element has no single truth value, so bool(arr) raises ValueError: The truth value of an array with more than one element is ambiguous. A pandas DataFrame or Series raises the same kind of error. This is deliberate: "is the array true" could mean any element, all elements or non-empty, and NumPy refuses to guess.

The explicit forms are arr.any(), arr.all(), arr.size == 0 and, for pandas, df.empty. For a one-element array, bool works, which makes the bug worse: code passes on small test data and fails on real data.

The lesson reaches beyond NumPy. The same if x: means "non-empty" for a list, "non-zero" for a number and "an error" for an array. When a function can receive several types, I test the property I mean (is None, len(x), .empty) so the line says what it checks.

"What should __bool__ mean for my class?"

It should answer one question: "is this object meaningfully non-empty, valid or non-zero?" Containers return true when they hold items. A Money value returns true when the amount is non-zero. A result object returns true on success, as re.Match does by being None or an object.

  1. Keep it cheap: __bool__ runs in every if x:, so no I/O and no heavy work.
  2. Return a real bool: returning 1 or a string raises TypeError.
  3. Document it: one line in the docstring, because readers will not guess whether a zero amount is falsy.

Do not define __len__ on a non-container just to get truthiness. Then len(x) also works and invites wrong uses, and list(x) or iteration code may be misled. Define __bool__ alone, and if the meaning is surprising, skip it and let callers write x.is_valid.

"What is the bug with x or default and a callable or datetime?"

The trap is that x or default replaces any falsy value, not only None. An object with no __bool__ or __len__ is always true, so a plain callable is safe. The trouble comes from values that are legitimately zero or empty.

q27_falsy.pyruns offline
price_bad(0)              -> 9.99
price_ok(0)               -> 0
price_bad(Decimal("0"))   -> 9.99
price_ok(Decimal("0"))    -> 0

Here price_bad is price or 9.99 and price_ok is price if price is not None else 9.99. A free item (price zero) turns into a 9.99 item. Zero, Decimal("0"), an empty string and an empty list all fall into this hole. datetime.time(0, 0) was also falsy before Python 3.5, which hid midnight bugs.

I use or for defaults only when every falsy value really should be replaced. Otherwise I write the is not None form.

Q28. "__repr__ versus __str__ — what makes a good __repr__?"

Reveal answer

Strong answer __repr__ is for developers: an unambiguous description, ideally one that looks like the code that rebuilds the object. __str__ is for users: a readable form. print(x) and f"{x}" call __str__; the REPL, debuggers, logs using %r, and the items inside a printed list call __repr__.

If you define only one, define __repr__, because str() falls back to it when __str__ is missing. The reverse does not happen.

A good __repr__ has the class name and enough field values to identify the object, uses repr() of the fields so strings show their quotes, and never raises (a failing __repr__ makes tracebacks and logging worse). Use the !r conversion in f-strings: f"Order(id={self.id!r}, total={self.total!r})". Dataclasses write a good one for you.

Keep it short. A repr that prints a ten-thousand-element list into every log line will hurt more than help.

Picture it The same object printed three ways, and how containers choose.

The setup: A class with a good __repr__ and a separate __str__.

q28_repr_str.py · Python 3.14runs offline
from dataclasses import dataclass
from decimal import Decimal

class Order:
    def __init__(self, id, total):
        self.id, self.total = id, total
    def __repr__(self):
        return f"Order(id={self.id!r}, total={self.total!r})"
    def __str__(self):
        return f"Order #{self.id} for ${self.total}"

o = Order("A-17", Decimal("19.50"))
print("print(o)  :", o)
print("repr(o)   :", repr(o))
print("in a list :", [o])
print("f'{o!r}'  :", f"{o!r}")
print("'%s' / '%r':", "%s" % o, "/", "%r" % o)

@dataclass
class Line:
    sku: str
    qty: int
print("dataclass  :", Line("SKU-1", 3))
print("str vs repr of a str:", str("hi"), repr("hi"), "| of Decimal:", str(Decimal("1.5")), repr(Decimal("1.5")))
output · Python 3.14runs offline
print(o)  : Order #A-17 for $19.50
repr(o)   : Order(id='A-17', total=Decimal('19.50'))
in a list : [Order(id='A-17', total=Decimal('19.50'))]
f'{o!r}'  : Order(id='A-17', total=Decimal('19.50'))
'%s' / '%r': Order #A-17 for $19.50 / Order(id='A-17', total=Decimal('19.50'))
dataclass  : Line(sku='SKU-1', qty=3)
str vs repr of a str: hi 'hi' | of Decimal: 1.5 Decimal('1.5')

What you see: print(o) uses the friendly form, while the list shows Order(...) because containers print their items with repr. The dataclass produced a repr by itself, and repr of a string keeps the quotes that str drops.

Why: print asks the object for its readable form; containers cannot guess, so they ask for the unambiguous one.

Only __str__

Logs lose the type.

onlystr.pyruns offline
def __str__(self):
    return f"Order #{self.id}"
# [o] prints <Order object at 0x..>

__repr__ first

Debug output is clear.

repr.pyruns offline
def __repr__(self):
    return (f"Order(id={self.id!r}, "
            f"total={self.total!r})")

The shift: Write __repr__ for the person debugging at 3 a.m.; add __str__ only if users need a different face.

Land it I always write __repr__ as ClassName(field=value!r, ...) that never raises, and add __str__ only when a human-readable form is genuinely different.

Likely follow-ups
"Should repr be evaluable by eval?"

It is a goal, not a rule. If the repr is cheap and obvious, make it look like the constructor call, for example Money(Decimal('1.50'), 'USD'). Then you can paste it from a log into a test and rebuild the object. That alone saves minutes during an incident.

Often it cannot be done honestly. An object that holds a socket, a file handle or a ten-million-row table has no short code that rebuilds it. The convention for that case is angle brackets: <Session id=7 state='open'>. The brackets tell the reader "this is a description, do not eval it".

Never call eval on a repr from outside, because that is code execution on text. For round trips use json, pickle or ast.literal_eval.

What matters most is that two different objects of the same class can be told apart in a log. Include the id or the key fields, and leave out the bulk.

"How do I avoid leaking secrets in repr?"

Reprs travel far. They end up in log lines, exception messages, debugger panels and error trackers that store them for months. So anything in a repr should be safe to read on a shared dashboard.

  1. Dataclasses: mark the field field(repr=False) and it disappears from the generated repr.
  2. Pydantic: use SecretStr; its repr and str show **********, and you call .get_secret_value() only where the value is needed.
  3. Handwritten reprs: list the fields you want, rather than dumping self.__dict__, so a new secret field is not leaked by default.

Passwords, API keys, card numbers and personal data (phone, email, address) all belong on the do-not-print list. Also watch exception messages, which often embed repr(obj) of the failing object. A good test is to build an object with a recognisable fake secret and assert that the secret is absent from repr(obj).

"What does !r, !s and format() do?"

They are three ways to ask an object for text inside an f-string. {x!r} calls repr(x), {x!s} calls str(x), and {x:spec} calls format(x, "spec"), which reaches x.__format__("spec"). Without any marker, {x} is the same as format(x, "").

q28_repr.pyruns offline
{o!r} -> Order(id=7, note='no onions')
{o!s} -> Order(id=7, note='no onions')
{o}   -> order #7
{n=}  -> n='7'
[o]   -> [Order(id=7, note='no onions')]

This class defines __repr__ and a custom __format__ but no __str__. So !s falls back to the repr, while the plain {o} uses my __format__. The default object.__format__ only accepts an empty spec and then calls str. Numbers and dates define their own spec languages, such as :.2f and :%Y-%m-%d.

The {n=} form (Python 3.8 and later) prints the expression text and then its repr, so n='7' shows the quotes. It is the quickest debugging print, and the repr tells you at a glance whether the value was a string or a number.

"What if repr raises an exception?"

Then every place that formats the object fails when it runs the repr: print, tracebacks, debuggers, and log calls with %r. The worst case is the failure hiding the real error. Logging catches exceptions raised while formatting a message and prints --- Logging error --- to standard error instead, so the original log line is lost.

The typical causes are a repr that touches a field not yet set (during __init__ or after a half-finished copy), one that does I/O such as a lazy database load, and one that recurses through objects that refer to each other.

I keep __repr__ free of I/O and lazy loading, and I read fields defensively, for example getattr(self, "id", "?"). For parent-child links, print only the id of the other object. The standard reprlib module and @reprlib.recursive_repr() handle size limits and cycles when needed.

Q29 · Scenario. "Your class supports a + b, but sum(list_of_them) fails. Why, and what is the fix?"

Reveal answer

Strong answer sum(items) does not start from the first item. It starts from the integer 0 and computes 0 + items[0], then result + items[1], and so on. So the very first operation is int.__add__(0, item), which returns NotImplemented, and Python then tries item.__radd__(0). If your class defines only __add__, there is no __radd__, and you get TypeError: unsupported operand type(s) for +: 'int' and 'Money'.

Two clean fixes. Give sum a proper starting value: sum(items, start=Money.zero()) (the start keyword exists since 3.8). This is explicit and my default. Or add __radd__ that accepts 0: def __radd__(self, other): return self if other == 0 else self.__add__(other).

The __radd__ trick makes sum(items) work with no ceremony, at the cost of a special case for 0. For a type with an obvious zero, a class-level zero() and a start= argument is clearer.

Alternatives for non-numeric "adding": functools.reduce(operator.add, items) fails on an empty list unless you give an initial value, and str.join is the right tool for strings (Q107).

Picture it The failure, the two fixes, and the empty-list case.

The setup: A small Points class that supports + only.

q29_sum_radd.py · Python 3.14runs offline
from functools import reduce
import operator

class Points:
    def __init__(self, n):
        self.n = n
    def __add__(self, other):
        if not isinstance(other, Points):
            return NotImplemented
        return Points(self.n + other.n)
    def __repr__(self):
        return f"Points({self.n})"

items = [Points(1), Points(2), Points(3)]
try:
    sum(items)
except TypeError as e:
    print("sum(items) ->", e)

print("fix 1, start=:", sum(items, start=Points(0)))

class Points2(Points):
    def __radd__(self, other):
        return self if other == 0 else self.__add__(other)

items2 = [Points2(1), Points2(2), Points2(3)]
print("fix 2, __radd__:", sum(items2))
print("empty list with start:", sum([], start=Points(0)), "| with radd only:", sum([]))
try:
    reduce(operator.add, [])
except TypeError as e:
    print("reduce on empty ->", e)
output · Python 3.14runs offline
sum(items) -> unsupported operand type(s) for +: 'int' and 'Points'
fix 1, start=: Points(6)
fix 2, __radd__: Points(6)
empty list with start: Points(0) | with radd only: 0
reduce on empty -> reduce() of empty iterable with no initial value

What you see: the first call fails at 0 + Points(1); both fixes work; and sum([]) with only __radd__ returns the plain integer 0, a type surprise, while start= returns a proper Points(0).

Why: sum begins with 0, and the first addition is 0 + first_item, which needs the reflected method on the right operand.

Only __add__

0 + p has nobody to ask.

onlyadd.pyruns offline
sum([Points(1), Points(2)])
# TypeError: int + Points

With start=

Give sum its own zero.

start.pyruns offline
sum([Points(1), Points(2)],
    start=Points(0))
# Points(3)

The shift: sum is a fold with a seed: pass a seed of your own type, or teach the type to accept 0.

Land it I say sum starts from 0, so I either pass start= of my own type or add a __radd__ that accepts 0, and I prefer start= because it is explicit.

Likely follow-ups
"Why does sum not just use the first element?"

Because sum has to return something for an empty iterable, and the documented contract is "the start value, default 0". If it took the first element as the start, sum([]) would have nothing to return and would have to raise.

Two other designs exist, and the comparison is useful. functools.reduce without an initial value does take the first element, and raises on an empty sequence. max and min do the same unless you give default=.

q29_sum.pyruns offline
sum(["a", "b"])      -> unsupported operand type(s) for +: 'int' and 'str'
max([])             -> max() iterable argument is empty
max([], default=0)  -> 0

With a fixed start of 0, the first step is always 0 + item, which is why a class needs __radd__ or a start= value. In my own code I choose by the empty case: if "no items" has a natural answer (a zero total), I use sum with start=; if it is an error, reduce is fine.

"Does the same thing apply to max, min and sorted?"

Partly. They compare items instead of adding, so they need __lt__ (or a key= function) and no zero value. sorted and list.sort need only __lt__, while max and min also use the order operators between items.

The empty case is the difference. sorted([]) returns [], but max([]) and min([]) raise ValueError: max() iterable argument is empty, because there is no sensible biggest of nothing. Passing default= returns your value instead.

A classic production bug is max(prices) on a list that is empty during a quiet hour, so the dashboard breaks at 4 a.m. only. max(prices, default=0) is the cheap fix, provided zero is a sensible answer for you. If it is not, None as the default, with a check, is better than a made-up number.

A key= function is called once per item, so keep it light.

"Is sum fine for floats?"

Be careful with the claim. The error in 0.1 + 0.2 == 0.30000000000000004 comes from the numbers, not from the summing. The decimal fraction 0.1 has no exact binary form, so the stored value is already slightly off. No sum function can undo that.

What sum adds on top is accumulation error: each running total is rounded. math.fsum avoids it and rounds only once at the end. Recent Python versions (3.12 on) already make sum of floats more accurate with compensated summation, so the gap is smaller than old advice says. Check your version's notes before quoting a difference.

My rule: for statistics and measurements, sum or fsum is fine. For money, never use floats at all. Use Decimal or integer cents (Q10). Also, sum refuses a list of strings on purpose, with a hint to use "".join, because repeated concatenation copies the string every time and is quadratic.

"How do I make my type work with sum, abs and round?"

Each built-in function is a thin front for one special method on the type, as in Q21. So you make your type work by defining the method behind each function.

  1. sum: define __radd__ that accepts 0, or tell callers to pass start=Money.zero(). I prefer the explicit start=.
  2. abs: define __abs__. For a vector it is the length, for money the absolute amount.
  3. round: define __round__(self, ndigits=None). Return the same type when ndigits is given.

The same idea covers len (__len__), bool, hash, int and float (__int__, __float__), and divmod.

If the type should behave like a number, the numbers module gives abstract bases that document the contract. If it needs the full set of comparisons, define __eq__ and __lt__ and add functools.total_ordering. I define only what the domain needs, because every extra operator is something to test.

Q30 · Design. "Design a Vector type that works with operators, iteration, hashing, equality and printing."

Reveal answer

Strong answer I decide the contract before writing methods. A Vector is a value: fixed length, components never change. So it is immutable, stored as a tuple, with equality and hash over the components.

Mapping from behaviour to special method: construction __init__(*parts); printing __repr__ (and __str__ if wanted); iteration and unpacking __iter__; size and indexing __len__, __getitem__; addition and subtraction __add__, __sub__, negation __neg__; scaling __mul__ and __rmul__ so both v * 2 and 2 * v work; length __abs__; dot product __matmul__ (the @ operator); truthiness __bool__ (non-zero); equality and hashing __eq__, __hash__.

The rules that make it correct: return NotImplemented for foreign operand types, check lengths and raise a clear ValueError, keep __eq__ and __hash__ consistent (Q22), and never mutate. If someone needs a large numeric vector in speed-critical code, this class is the wrong tool: use NumPy.

Picture it The class and a session using each protocol.

The setup: An immutable Vector backed by a tuple, then used with operators, unpacking, sets and sum.

q30_vector.py · Python 3.14runs offline
import math

class Vector:
    __slots__ = ("_c",)

    def __init__(self, *parts):
        object.__setattr__(self, "_c", tuple(float(p) for p in parts))
    def __setattr__(self, name, value):
        raise AttributeError("Vector is immutable")
    def __iter__(self):
        return iter(self._c)
    def __len__(self):
        return len(self._c)
    def __getitem__(self, i):
        return self._c[i]
    def __repr__(self):
        return f"Vector({', '.join(map(repr, self._c))})"
    def __eq__(self, other):
        if not isinstance(other, Vector):
            return NotImplemented
        return self._c == other._c
    def __hash__(self):
        return hash(self._c)
    def __bool__(self):
        return any(self._c)
    def __abs__(self):
        return math.hypot(*self._c)
    def __neg__(self):
        return Vector(*(-x for x in self._c))
    def _pair(self, other, op):
        if not isinstance(other, Vector):
            return NotImplemented
        if len(self) != len(other):
            raise ValueError("vectors must have the same length")
        return Vector(*(op(a, b) for a, b in zip(self, other)))
    def __add__(self, other):
        return self._pair(other, lambda a, b: a + b)
    def __sub__(self, other):
        return self._pair(other, lambda a, b: a - b)
    def __mul__(self, k):
        if not isinstance(k, (int, float)):
            return NotImplemented
        return Vector(*(x * k for x in self._c))
    __rmul__ = __mul__
    def __radd__(self, other):
        return self if other == 0 else NotImplemented
    def __matmul__(self, other):
        return sum(a * b for a, b in zip(self, other))

v, w = Vector(3, 4), Vector(1, 2)
print(v + w, "|", v - w, "|", -v, "|", v * 2, "|", 2 * v)
print("abs:", abs(v), "| dot:", v @ w, "| len:", len(v), "| v[1]:", v[1])
x, y = v
print("unpacked:", x, y, "| list:", list(v))
print("equal:", Vector(3, 4) == v, "| set size:", len({v, Vector(3, 4), w}))
print("bool:", bool(Vector(0, 0)), bool(v), "| sum:", sum([v, w, v]))
print("v == (3, 4):", v == (3.0, 4.0))
try:
    v + Vector(1, 2, 3)
except ValueError as e:
    print("length mismatch ->", e)
try:
    v._c = ()
except AttributeError as e:
    print("edit ->", e)
output · Python 3.14runs offline
Vector(4.0, 6.0) | Vector(2.0, 2.0) | Vector(-3.0, -4.0) | Vector(6.0, 8.0) | Vector(6.0, 8.0)
abs: 5.0 | dot: 11.0 | len: 2 | v[1]: 4.0
unpacked: 3.0 4.0 | list: [3.0, 4.0]
equal: True | set size: 2
bool: False True | sum: Vector(7.0, 10.0)
v == (3, 4): False
length mismatch -> vectors must have the same length
edit -> Vector is immutable

What you see: every protocol works on one class: operators, unpacking, len, indexing, hashing in a set, truthiness, sum and clear errors. v == (3, 4) is False because __eq__ returned NotImplemented for a tuple and the tuple declined too.

Why: each behaviour is one small special method; consistency between __eq__ and __hash__ is what makes sets and dict keys safe.

Land it I model it as an immutable value on a tuple, map every behaviour to its special method, return NotImplemented for foreign types, and keep equality and hash on the same components.

Likely follow-ups
"Why not subclass tuple?"

Subclassing tuple gives you immutability, hashing, indexing and iteration for free, and the first three things you want from a Vector. The cost is that tuple behaviour leaks into your public surface.

q30_vector.pyruns offline
Tup((1, 2)) + Tup((3, 4))  -> (1, 2, 3, 4)

For a Vector, v + w must add component by component, but the inherited + concatenates, and it returns a plain tuple, not your class. Slicing, in, count, index and tuple equality (Vector(1, 2) == (1, 2) is true) all come along too, and some of them are wrong for a mathematical vector.

Composition, meaning a hidden _parts tuple inside a normal class, keeps the public API exactly the protocol I chose. I subclass only for thin variants, where the type really is a tuple with names, such as NamedTuple.

"Would you use a dataclass here?"

Yes, it is a fair shortcut. A @dataclass(frozen=True) with one field components: tuple[float, ...] generates __init__, __eq__, __hash__ and __repr__. Frozen blocks assignment, and with eq=True and frozen=True the hash is built from the fields, so equality and hashing stay consistent (Q22).

I would then write only the behaviour that is special: __add__, __mul__, __rmul__, __abs__, __matmul__, __iter__ and __len__.

What I would watch is the constructor and the repr. The generated __init__ takes one tuple argument, so Vector((1, 2)), not Vector(1, 2). To get the nicer call I would add a classmethod, or write __init__ by hand. The generated repr shows Vector(components=(1, 2)), which is accurate but wordy. Adding slots=True saves memory when many are created.

In the answer I wrote it by hand to show each special method. In a codebase I would use the dataclass.

"How do I make v * 2.5 and np.float64 work?"

The check isinstance(k, (int, float)) accepts np.float64, because that class inherits from Python's float. It does not accept np.int64, which is not an int subclass. A more general test is isinstance(k, numbers.Real), which both NumPy types satisfy through registration.

q30_vector.pyruns offline
isinstance(np.int64(2), int)           -> False
isinstance(np.int64(2), numbers.Real)  -> True
isinstance(np.float64(2), float)       -> True

Operand order is the second trap. With a NumPy array on the left, arr * v gets the first try, and NumPy may treat your object as a scalar to broadcast over, so it calls your __rmul__ once per element. Setting __array_ufunc__ = None on your class tells NumPy to return NotImplemented, so your reflected method runs once, on the whole array.

q30_vector.pyruns offline
array * W() -> ['rmul' 'rmul']
array * V() -> rmul

I would add a test with each numeric type on both sides of the operator.

"When should I not build this class at all?"

When vectors are long or the maths is heavy. A hand-made class means one Python object per vector and a Python loop per operation, and each number inside is a separate Python object with its own header. NumPy keeps numbers packed in one block and runs the loop in compiled code, so for a vector of a few thousand numbers it is usually tens to hundreds of times faster. Measure with your own sizes (Q19, Q110).

Also skip the class when the type already exists. For geometry, finance or data science, numpy arrays, fractions.Fraction or decimal.Decimal are better tested than anything I would write in an afternoon.

A hand-written value class is right for small domain types, such as a 2D point, a money amount, a version number or a time range. There, clarity and correct ==, hashing and printing matter more than speed. The question I ask is "how many of these exist, and how big is each?" Few and small, write the class. Many or big, use arrays.

Drill · Attribute lookup, classes and metaprogramming

These questions test whether you can state the exact algorithm behind obj.attr, and then use it to explain properties, slots, inheritance order and class creation.

Q31. "Walk through exactly how obj.attr is resolved."

Reveal answer

The real test Whether you name the priority order: data descriptor on the type, then the instance dict, then non-data descriptor or class attribute, then __getattr__.

Strong answer obj.attr calls type(obj).__getattribute__(obj, "attr"), whose default implementation follows four steps in strict order.

  1. 1. Data descriptor on the type. Search the class and its bases in MRO order (Q34). If the name is found and the object has __set__ or __delete__ (a data descriptor, such as property), call its __get__. It wins over the instance dictionary.
  2. 2. Instance dictionary. If obj.__dict__ has the name, return that value.
  3. 3. Non-data descriptor or plain class attribute. If step 1 found a descriptor with only __get__ (every function is one), call it, which makes a bound method. If it found an ordinary value, return it.
  4. 4. __getattr__. If everything failed and the class defines __getattr__, call it. Otherwise raise AttributeError.

The order explains known facts. A property cannot be overridden by assigning into the instance dict, because data descriptors win. A method can be shadowed by an instance attribute of the same name, because functions are non-data descriptors, so the instance dict wins. Assignment obj.attr = v has its own, shorter path: look for a data descriptor with __set__ on the type, otherwise write into obj.__dict__.

Picture it Four attributes with the same name set at every level, so the winner is visible.

The setup: A class with a data descriptor, a non-data descriptor, a plain class attribute, a method, and a __getattr__; the instance dict is filled by hand with values of the same names.

q31_attribute_order.py · Python 3.14runs offline
class DataDesc:
    def __get__(self, obj, owner):
        print("    -> data descriptor __get__")
        return "value from data descriptor"
    def __set__(self, obj, value):
        pass                                       # having __set__ makes it a DATA descriptor

class NonDataDesc:
    def __get__(self, obj, owner):
        print("    -> non-data descriptor __get__")
        return "value from non-data descriptor"

class A:
    d = DataDesc()
    n = NonDataDesc()
    c = "class attribute"
    def method(self):
        return "the real method"
    def __getattr__(self, name):
        print("    -> __getattr__ fallback")
        return f"fallback for {name!r}"

a = A()
a.__dict__.update(d="instance d", n="instance n", c="instance c")   # same names, instance level

print("a.d     (data descriptor vs instance dict):", a.d)
print("a.n     (non-data descriptor vs instance dict):", a.n)
print("a.c     (class attribute vs instance dict):", a.c)
a.__dict__["method"] = lambda: "shadowing lambda"
print("a.method() with instance override:", a.method())
print("A().method() on a clean instance :", A().method())
print("a.nothing:", a.nothing)
output · Python 3.14runs offline
    -> data descriptor __get__
a.d     (data descriptor vs instance dict): value from data descriptor
a.n     (non-data descriptor vs instance dict): instance n
a.c     (class attribute vs instance dict): instance c
a.method() with instance override: shadowing lambda
A().method() on a clean instance : the real method
    -> __getattr__ fallback
a.nothing: fallback for 'nothing'

What you see: the data descriptor beats the instance value, the instance value beats the non-data descriptor and the class attribute, an instance entry can shadow a method, and only a total miss reaches __getattr__.

Why: the two descriptor kinds differ only in whether they define __set__ or __delete__, and that single difference moves them above or below the instance dictionary.

Land it I recite the order: data descriptor on the type, instance __dict__, non-data descriptor or class attribute, then __getattr__, and use it to explain why properties cannot be shadowed and methods can.

Likely follow-ups
"Where does the MRO come in?"

The MRO (method resolution order, Q34) is the ordered list of the class and all its bases. Steps 1 and 3 walk that list from the front and take the first class whose __dict__ has the name. So a subclass attribute hides a base attribute of the same name, and with multiple inheritance the C3 order decides who is first.

The instance dictionary is outside that search. It belongs to one object, so Python checks it once, between the two class-side steps. It does not look for the name in parents' instance dictionaries, because there are none: every instance has exactly one.

A short example. If Base defines rate = 1 and Child(Base) defines rate = 2, then Child().rate is 2 because Child comes first in the MRO. Writing child.rate = 3 creates an entry in that one instance's dictionary and changes nothing on the classes.

When a lookup surprises me, I print type(obj).__mro__ first.

"What changes with __slots__?"

The instance __dict__ disappears, so step 2 finds nothing to look in. In its place the class gets one member descriptor per slot name, and each is a data descriptor, so step 1 handles reads and writes. Point.x prints as <member 'x' of 'Point' objects>. The value itself sits at a fixed offset inside the object, one pointer per slot.

Assigning a name that is not a slot finds no descriptor and no dictionary, so you get AttributeError. That is also how slots catch typos such as obj.amout = 1.

The memory saving is real. In this chapter's measurement, one million small instances took 104.5 MB with a dictionary each and 64.4 MB with slots, on Python 3.14. That is 40 bytes less per object, about 38 % in this test.

Normal attribute syntax stays the same, so the cost is the restriction on new names and the missing __dict__ (Q33), not any change in how you write code.

"How does this relate to __getattribute__ and class attributes?"

Looking up A.attr on the class itself follows the same shape, one level up. The "type" of a class is its metaclass, usually type. Python first checks the metaclass for a data descriptor, then looks through the class's own __dict__ and its bases (the MRO), then falls back to a metaclass non-data descriptor or plain attribute, and last to the metaclass __getattr__.

The difference you can see is in what __get__ receives. For a.attr it is called as __get__(descr, a, A). For A.attr it is called as __get__(descr, None, A), with None for the instance. A well-written descriptor checks for that and, when the instance is None, returns itself (Q40).

This explains familiar behaviour. A plain function accessed on the class is just a function, since it returns itself when there is no instance. On an instance it becomes a bound method. classmethod binds to the class in both cases, and property accessed on the class returns the property object, which is how documentation tools find it.

"Does the interpreter really do all this on every access?"

Conceptually yes, in practice no. The rules above are the meaning of the language. The speed comes from CPython remembering earlier answers. Since Python 3.11 the specialising interpreter (PEP 659, Q63) watches hot bytecode. After a few runs of self.x on instances of the same class, it rewrites that instruction into a specialised form that skips the four-step search.

The shortcut is safe because of a guard. Each class carries a version tag that changes whenever the class or one of its bases is modified. The specialised instruction checks the tag first. If it matches, it jumps straight to the stored position of the value. If not, the instruction falls back to the full lookup and may specialise again.

So the cost of a repeated attribute read is a version check plus a load, which is why plain reads take about ten nanoseconds (Q33). Patching a class at run time throws these caches away, so do it at start-up and not inside hot code. Overriding __getattribute__ also gives up much of the speed-up (Q26).

Q32. "What is a descriptor? Show how property, methods and staticmethod are descriptors."

Reveal answer

Strong answer A descriptor is an object stored as a class attribute that defines __get__, and optionally __set__ and __delete__. When an attribute lookup finds a descriptor on the class (Q31), Python calls its __get__(self, instance, owner) instead of returning the object itself.

Everything you know is built on that. A function defined in a class has __get__; given an instance it returns a bound method, a small object that remembers the instance and passes it as self. That is why obj.method() works. staticmethod's __get__ returns the plain function untouched. classmethod's returns the function bound to the class. property has __get__ calling your getter, and __set__ calling your setter, which makes it a data descriptor.

__set_name__(owner, name) is a hook called once when the class is created, which lets a descriptor learn the attribute name it was assigned to; this is how a reusable validated field can store its value under the right key (Q40).

Descriptors are for behaviour that must be shared across many attributes or classes. A single computed attribute is a property; the same rule on twenty attributes is a descriptor.

Picture it What each kind of class attribute really is, and a hand-written property.

The setup: Inspect Demo.__dict__ for each attribute, bind a method manually, and re-implement property in eight lines.

q32_descriptors.py · Python 3.14runs offline
class Demo:
    def method(self):
        return "method result"
    @staticmethod
    def sm():
        return "static result"
    @classmethod
    def cm(cls):
        return f"class method on {cls.__name__}"
    @property
    def p(self):
        return 42

d = Demo()
for name in ("method", "sm", "cm", "p"):
    attr = Demo.__dict__[name]
    print(f"{name:7} stored as {type(attr).__name__:13} __get__: {hasattr(attr, '__get__')!s:5} __set__: {hasattr(attr, '__set__')}")

print("Demo.method     :", Demo.method)
print("d.method        :", d.method)
bound = Demo.__dict__["method"].__get__(d, Demo)           # what d.method does
print("manual __get__  :", bound(), "| self is d:", bound.__self__ is d)

class MyProperty:                                          # property in 8 lines
    def __init__(self, fget):
        self.fget = fget
    def __get__(self, obj, owner=None):
        return self if obj is None else self.fget(obj)
    def __set__(self, obj, value):
        raise AttributeError("read-only attribute")

class Box:
    @MyProperty
    def size(self):
        return 7

b = Box()
print("b.size =", b.size)
try:
    b.size = 9
except AttributeError as e:
    print("assignment ->", e)
output · Python 3.14runs offline
method  stored as function      __get__: True  __set__: False
sm      stored as staticmethod  __get__: True  __set__: False
cm      stored as classmethod   __get__: True  __set__: False
p       stored as property      __get__: True  __set__: True
Demo.method     : <function Demo.method at 0x7f41ec69f270>
d.method        : <bound method Demo.method of <__main__.Demo object at 0x7f41ec690590>>
manual __get__  : method result | self is d: True
b.size = 7
assignment -> read-only attribute

What you see: methods, staticmethod, classmethod and property objects all sit in the class dict, all have __get__, and only property has __set__. A function turns into a bound method when it is fetched through an instance.

Why: lookup finds the descriptor on the class and calls its __get__, so the attribute you receive is whatever __get__ returns, not the stored object.

Java · Spring

Getters and setters by hand.

Box.javaruns offline
private int size;
public int getSize() {
  return size;
}
// callers must write getSize()

Python

Plain attribute now, property later.

box.pyruns offline
class Box:
    @property
    def size(self):
        return self._size
# callers still write box.size

The shift: Python callers never see the difference between a field and a computed attribute, because the descriptor protocol sits behind the dot. See the descriptor idiom.

Land it I define a descriptor as a class attribute with __get__ (and maybe __set__), and show that functions, staticmethod, classmethod and property are all examples, with bound methods created by function __get__.

Likely follow-ups
"What is the difference between a data and a non-data descriptor?"

A data descriptor defines __set__ or __delete__ in addition to __get__. A non-data descriptor defines only __get__. The difference decides who wins against the instance dictionary (Q31): a data descriptor on the class beats the instance dictionary, and a non-data descriptor loses to it.

q31_shadow.pyruns offline
a.method -> instance value
a.prop   -> property
a.prop = 1 -> property 'prop' of 'A' object has no setter

Here I put an entry named method and one named prop straight into the instance dictionary. The function (non-data) is shadowed, while the property (data) ignores the entry. A property without a setter still defines __set__, which raises, so assigning fails instead of creating a shadow.

Design rule: if the attribute must not be overridden per instance, make it a data descriptor. If per-instance overrides are fine or wanted, a non-data descriptor is enough, as with cached_property.

"Why is a bound method a new object on each access?"

Because each time you write obj.method, the function's __get__ builds a new bound-method object. It is a small wrapper holding two references: the instance (__self__) and the underlying function (__func__). When you call it, it passes the instance as the first argument.

q32_bound.pyruns offline
a.m is a.m  -> False
a.m == a.m  -> True
a.m.__self__ is a   -> True
a.m.__func__ is A.m -> True

Two evaluations give two objects, so is says False, while == compares the pair (instance, function) and says True. That matters when you register and later remove a callback. Compare with == or keep the one bound method in a variable, and never rely on is.

The allocation is cheap, and the specialising interpreter avoids it for direct calls like obj.method(). A bound method also keeps its instance alive, so a stored callback can hold an object in memory longer than you expect. For that case look at weakref.WeakMethod (Q15).

"Where do I use __set_name__?"

It is used inside a reusable descriptor, to let the descriptor learn the name it was assigned to. Python calls __set_name__(self, owner, name) once for each descriptor in the class namespace, when the class object is created.

  1. Store the name: keep name, and optionally "_" + name as the storage key.
  2. Use it in __get__ and __set__: read and write obj.__dict__[self.name] or getattr(obj, self.private), so one descriptor class serves any number of fields.
  3. Use it in errors: messages such as qty must be between 1 and 1000 can name the field and the class.

Before Python 3.6 there was no such hook. You had to write qty = Ranged("qty", 1, 1000), repeating the name as a string, and a typo in either place gave a silent bug. The hook runs only when the class is created. A descriptor assigned later, as in Cls.f = Ranged(...), does not get the call, so I call __set_name__ by hand in that case.

"Does functools.cached_property use this?"

Yes. functools.cached_property is a non-data descriptor. On the first access it calls your function, then stores the result in the instance __dict__ under the same name. On the next access, step 2 of the lookup (Q31) finds that entry before the descriptor is considered, so the function is never called again. It also means the cache is plain data: del obj.name clears it, and the value is computed again.

The consequences follow from how it works. It needs an instance __dict__, so it fails on classes with plain __slots__; adding "__dict__" to the slots restores one. It caches per instance, with no key and no size limit, and the value lives exactly as long as the object. That makes it the safe replacement for @lru_cache on a method (Q50).

Thread safety changed between versions. Older versions took a lock around the first computation, and newer ones removed it, so two threads that miss together may both run the function. Check the docs for your version, and make the function pure.

Q33. "What do __slots__ do, and what do they cost you?"

Reveal answer

Strong answer __slots__ = ("a", "b") tells Python that instances have exactly these attributes. Instead of a per-instance __dict__, Python gives each instance fixed storage slots, one pointer per name. Each slot is exposed through a data descriptor on the class (Q31).

The gain is memory: no dictionary per object. For many small objects the saving is large, typically 40 % to 60 %, and attribute access is similar or slightly faster. Typos such as obj.amout = 1 raise AttributeError instead of creating a new attribute.

The costs: you cannot add attributes that are not declared; there is no __dict__ so anything relying on it (vars(obj), cached_property, some serialisers) needs care; no weak references unless you add "__weakref__" to the slots; multiple inheritance gets awkward (at most one base class with non-empty slots); and defaults need __init__ because a slot name cannot also be a class attribute with a default.

Use them on classes with millions of instances. Do not add them everywhere; the readability cost is small but real. @dataclass(slots=True) (3.10+) applies them without the boilerplate.

Picture it Memory for a million instances with and without slots, and the restrictions.

The setup: Two identical classes, a million instances of each, measured with tracemalloc.

q33_slots.py · Python 3.14runs offline
import tracemalloc, timeit

class Plain:
    def __init__(self, a, b, c):
        self.a, self.b, self.c = a, b, c

class Slotted:
    __slots__ = ("a", "b", "c")
    def __init__(self, a, b, c):
        self.a, self.b, self.c = a, b, c

N = 1_000_000
for cls in (Plain, Slotted):
    tracemalloc.start()
    objs = [cls(1, 2, 3) for _ in range(N)]
    cur, _ = tracemalloc.get_traced_memory()
    tracemalloc.stop()
    print(f"{cls.__name__:8} {N:,} instances: {cur / 1e6:6.0f} MB   ({cur / N:.0f} bytes each)")
    del objs

s = Slotted(1, 2, 3)
for stmt, label in (("s.a = 5", "assign declared"), ("s.zzz = 5", "assign undeclared"), ("s.__dict__", "read __dict__")):
    try:
        exec(stmt)
        print(f"{label:18} -> ok")
    except AttributeError as e:
        print(f"{label:18} -> AttributeError: {e}")

p, s = Plain(1, 2, 3), Slotted(1, 2, 3)
print("read p.a  :", f"{timeit.timeit('p.a', globals=globals(), number=5_000_000) * 200:.0f} ns per access")
print("read s.a  :", f"{timeit.timeit('s.a', globals=globals(), number=5_000_000) * 200:.0f} ns per access")
output · Python 3.14runs offline
Plain    1,000,000 instances:    104 MB   (104 bytes each)
Slotted  1,000,000 instances:     64 MB   (64 bytes each)
assign declared    -> ok
assign undeclared  -> AttributeError: 'Slotted' object has no attribute 'zzz' and no __dict__ for setting new attributes
read __dict__      -> AttributeError: 'Slotted' object has no attribute '__dict__'
read p.a  : 12 ns per access
read s.a  : 11 ns per access
# measured on the course machine; your numbers will differ

What you see: the slotted version uses about 40 % less memory (64 bytes instead of 104 per instance); the declared attribute is writable, the undeclared one and __dict__ raise AttributeError, and read speed is about the same.

Why: no per-instance dictionary: each value lives in a fixed position in the object, and the class holds one descriptor per slot.

Plain class

Each instance carries a dict.

plain.pyruns offline
class P:
    def __init__(self, a):
        self.a = a
p.extra = 1       # allowed

__slots__

Fixed fields, smaller object.

slotted.pyruns offline
class P:
    __slots__ = ("a",)
    def __init__(self, a):
        self.a = a
p.extra = 1       # AttributeError

The shift: Slots trade flexibility for memory and typo safety. See the slots idiom.

Land it I use slots (or dataclass(slots=True)) for classes with very many instances, state the costs (no new attributes, no __dict__, no weakrefs by default, inheritance limits), and I measured the saving.

Likely follow-ups
"Does inheritance work with slots?"

Yes, but each class in the chain has to take part. If a subclass does not declare __slots__, its instances get a __dict__ again, and the memory saving is lost even though the base is slotted.

q33_slots_inherit.pyruns offline
Loose has __dict__: True
Tight has __dict__: False
multiple bases have instance lay-out conflict

Loose did not declare slots, so it has a dictionary. Tight declares only its new name b and has none. Do not repeat the parent's names in the subclass, because that wastes a second slot for the same name.

Two slotted bases with non-empty slots cannot be combined, since each wants its own fixed layout in memory. For mixins, I write __slots__ = (), which adds no layout. Then a mixin can sit next to one slotted base without the conflict. A chain where every class declares slots, from a root with __slots__ = (), is the clean pattern.

"How do I allow weak references or dynamic attributes with slots?"

Add the special names to the slots. __slots__ = ("a", "b", "__weakref__") allows weakref.ref(obj). Adding "__dict__" brings back a dictionary for undeclared names, on top of the fast declared slots.

  1. Weak references: needed by WeakValueDictionary, WeakSet and cache classes (Q15). Without "__weakref__" you get TypeError: cannot create weak reference to 'X' object.
  2. Dynamic attributes: "__dict__" lets users or libraries attach extra names. You keep the speed of the declared slots, but the dictionary is created for each object that uses it, so the memory purpose is partly defeated.
  3. Both: list them both if you really need both, which is rare.

Dataclass users can write @dataclass(slots=True, weakref_slot=True) in Python 3.11 and later to get the weakref slot. My default is to add only what a real need requires, because every extra slot gives back some of the saving.

"Are slots faster to read?"

Only a little, and not worth choosing for. I measured two million reads of one attribute. A plain instance took about 11.0 ns per read and a slotted one about 10.5 ns on Python 3.12. On 3.14 the numbers were 12.2 ns and 11.2 ns. The difference is real but within the noise of a normal machine.

The reason is the specialising interpreter (Q63). After warm-up, a read of a plain instance's attribute is also a cached check plus a load, so the dictionary lookup that slots avoid is mostly gone already. Before 3.11, the gap was larger.

The solid benefits are memory and safety. In the chapter's measurement, one million instances took 104.5 MB without slots and 64.4 MB with them on Python 3.14. A mistyped attribute name raises AttributeError instead of creating a silent new attribute. I say that in the interview, and I add that I measure on my own workload (Q110) before claiming any speed gain.

"What about pickling and copying?"

It works, with one old exception. In pickle protocol 2 and above, pickle saves and restores slot values by itself. copy.copy and copy.deepcopy use the same machinery, so they work too.

q33_pickle.pyruns offline
protocol 0 TypeError a class that defines __slots__ without defining __getstate__ cannot be pickled
protocol 2 ok 1 2
protocol 5 ok 1 2
copy: 2

Protocol 0 and 1 fail unless you define __getstate__ yourself. Modern code uses protocol 4 or 5, which is the default in recent versions, so the problem appears only when you are forced to talk to very old consumers.

The bigger risk is third-party code that assumes obj.__dict__ exists: some serialisers, vars(obj), ORMs and debugging tools. I add a round-trip test (dump, load, compare) for each slotted class that crosses a process boundary, and I check JSON or YAML libraries on one sample before adopting slots broadly.

Q34. "Explain the MRO and C3 linearisation using a diamond."

Reveal answer

Strong answer The MRO (method resolution order) is the list of classes Python searches, in order, when it looks up an attribute or calls super(). For a single chain it is just child, parent, grandparent. For multiple inheritance it must give one consistent order, which Python computes with C3 linearisation.

Take the diamond: D(B, C), B(A), C(A). The rule of C3 is: a class always comes before its parents, and the order in which you list the bases (B before C) is kept. Merging the lists [B, A], [C, A] and [B, C], we take B. Then A cannot be taken yet, because C (which also has A as a parent) must come first. Take C, then A. The MRO is D, B, C, A, object.

The key result: A appears once, and after both of its children. So a method defined in A is found only after B and C had their chance. When no consistent order exists (for example class X(A, B) with B a parent of A listed after it), Python refuses to create the class.

You can read the result anytime from D.__mro__ or D.mro().

Picture it A diamond, its MRO, a method found along the way, and an impossible class.

The setup: Four classes in a diamond, each with a who() method except C, plus a bad base order.

q34_mro.py · Python 3.14runs offline
class A:
    def who(self):
        return "A"

class B(A):
    def who(self):
        return "B"

class C(A):
    pass                                    # inherits who() from A, via the MRO

class D(B, C):
    pass

print("D.__mro__:", " -> ".join(k.__name__ for k in D.__mro__))
print("D().who() :", D().who())

class E(C, B):                              # opposite base order
    pass
print("E.__mro__:", " -> ".join(k.__name__ for k in E.__mro__))
print("E().who() :", E().who(), "(C has none, so B answers)")

try:
    class Bad(A, B):                        # A before its own child B: impossible
        pass
except TypeError as e:
    print("Bad ->", e)
output · Python 3.14runs offline
D.__mro__: D -> B -> C -> A -> object
D().who() : B
E.__mro__: E -> C -> B -> A -> object
E().who() : B (C has none, so B answers)
Bad -> Cannot create a consistent method resolution order (MRO) for bases A, B

What you see: D searches B first and finds B.who. E, with the bases reversed, passes through C (no who) and then B, never reaching A first, because A must come after both. The impossible order raises TypeError at class creation.

Why: C3 keeps each class before its parents and respects the written order of bases; if the two rules conflict, there is no valid linearisation.

Java · Spring

One parent, many interfaces.

D.javaruns offline
class D extends B implements C {
}
// state from one class only;
// default methods: pick one

Python

Many parents, one MRO.

d.pyruns offline
class D(B, C):
    pass
# D.__mro__ gives a single
# deterministic search order

The shift: Java avoids the diamond by allowing one parent class; Python allows it and resolves it with one predictable list.

Land it I compute the MRO by merging parent lists so every class precedes its parents and base order is kept, give D, B, C, A, object for the diamond, and read it with D.__mro__.

Likely follow-ups
"Why is the diamond a problem in other languages?"

Without a rule, there are two problems. First, which version of a method wins when B and C both override one from A? Second, does A's code run once or twice, since it is reachable by two paths? The "diamond" is the picture of that ambiguity.

Languages choose different answers. C++ allows multiple inheritance, and by default a diamond gives you two copies of A inside D. You ask for a single shared copy with virtual inheritance, and it is the programmer's job to remember to. Java dodges the question: a class may extend only one class, and interfaces with default methods must be resolved by hand when two collide.

Python gives a deterministic answer instead. C3 puts every class in one list, each class once, children before parents, with your base order kept. So A is searched after both B and C, and a cooperative super() chain (Q35) runs each method once. The price is that you must learn to read __mro__.

"How do I debug an unexpected method being called?"

Start with type(obj).__mro__ to see the search order. Then find the first class in that list that defines the name. The simplest tool is inspect.getattr_static(obj, name), which finds the attribute without running descriptors or __getattr__.

  1. Print the order: [c.__name__ for c in type(obj).__mro__].
  2. Find the owner: loop over the MRO and check name in vars(cls). The first hit is the winner for a normal method.
  3. Check the instance: look in vars(obj). An instance attribute can shadow a method (Q31).
  4. Check the call chain: if the winner calls super(), continue to the next class in the list.

Most "wrong method called" bugs come from one of three causes. The base order is not what you assumed (class D(C, B) versus class D(B, C)). A class in the middle forgot to call super(). Or an instance attribute has the same name as a method. The MRO list plus a quick look at vars(obj) finds all three.

"Does the MRO apply to __init__?"

Yes, __init__ is an ordinary method, so the first __init__ in the MRO runs. If it does not call super().__init__(), the others never run. The risk is silent: objects look fine until a field that a skipped initialiser should have set is read.

Calling the parent by name is the opposite mistake. The next script has one diamond with explicit calls and one with super().

q34_init.pyruns offline
by name : ['A', 'B', 'A', 'C']
super() : ['A', 'C', 'B']

With names, A runs twice, once from B and once from C. That is a real bug if A.__init__ opens a resource or appends to a list. With super(), each class runs once, in reverse order of the MRO because each calls up first and then does its own work. Q35 shows the keyword-argument pattern that makes the chain work.

"Should I design with multiple inheritance?"

Sparingly. The accepted use is a mixin: a small class with one purpose and no state of its own, written to be combined with a main base, as in class Handler(LoggingMixin, BaseHandler). Django's class-based views and many test frameworks use this style.

Deep hierarchies with several real parents are hard to follow. Every method can have four or five possible owners, and a change in one base can silently change the order for others. For anyone reading the code, the answer to "which method runs?" becomes a search through the MRO.

My default is composition: an object holds the collaborators it needs as fields and calls them. A Handler that has a logger and a store is easier to test, because you can pass fakes. When I need polymorphism without a shared base, I use a Protocol (Q117), where a class qualifies by having the right methods.

If you do use multiple inheritance, keep each class cooperative with super(), and test the MRO.

Q35. "How does super() work with multiple inheritance, and why is it called "cooperative"?"

Reveal answer

Strong answer super() does not mean "my parent". It means "the next class after me in the MRO of the instance's actual type". Inside B.method, super().method() calls the method of whatever class follows B in type(self).__mro__, and for a D object in the diamond that is C, not A.

That is why it is cooperative: each class does its part and then calls super() to pass control to the next class in line, without knowing who that is. If every class in the chain does it, each initialiser or method runs exactly once, in MRO order, even in a diamond.

The rules for it to work: every class in the chain must call super() (the chain breaks at the first one that does not); methods must accept and forward **kwargs so unknown arguments reach the class that wants them; and the last class before object consumes what is left, since object.__init__ rejects unexpected arguments.

Use it for mixins that add behaviour around a base (logging, validation) and for __init__ chains in diamonds.

Picture it A diamond where every class calls super(), and one that breaks the chain.

The setup: Four classes print when their __init__ runs; each forwards **kw.

q35_super_cooperative.py · Python 3.14runs offline
class A:
    def __init__(self, **kw):
        print("  A.__init__ (end of the chain)")
        super().__init__(**kw)

class B(A):
    def __init__(self, *, b=0, **kw):
        print(f"  B.__init__ b={b}")
        super().__init__(**kw)

class C(A):
    def __init__(self, *, c=0, **kw):
        print(f"  C.__init__ c={c}")
        super().__init__(**kw)

class D(B, C):
    def __init__(self, **kw):
        print("  D.__init__")
        super().__init__(**kw)

print("cooperative:")
D(b=1, c=2)

class Selfish(A):
    def __init__(self, **kw):
        print("  Selfish.__init__ (does NOT call super)")   # ❌ TRAP: chain broken

class D2(B, Selfish):
    def __init__(self, **kw):
        super().__init__(**kw)

print("broken chain (B, Selfish):")
D2(b=1)
print("MRO of D2:", [k.__name__ for k in D2.__mro__])
output · Python 3.14runs offline
cooperative:
  D.__init__
  B.__init__ b=1
  C.__init__ c=2
  A.__init__ (end of the chain)
broken chain (B, Selfish):
  B.__init__ b=1
  Selfish.__init__ (does NOT call super)
MRO of D2: ['D2', 'B', 'Selfish', 'A', 'object']

What you see: for D each initialiser runs once, in the order D, B, C, A, and b and c find their owners. With Selfish in the chain, everything after it (including A) is silently skipped.

Why: super() follows the instance's MRO, so every class must pass control onward or the rest of the chain never runs.

Java · Spring

super is the one parent.

B.javaruns offline
class B extends A {
  B() {
    super();   // always A
  }
}

Python

super is the next in line.

b.pyruns offline
class B(A):
    def __init__(self, **kw):
        super().__init__(**kw)
        # next in the MRO of type(self)

The shift: In Java super is a fixed parent; in Python it is the next class in a list that depends on the object's actual type.

Land it I explain super() as "next in the instance's MRO", and cooperative as every class forwarding **kwargs and calling super() so each runs exactly once.

Likely follow-ups
"Why keyword-only arguments in the chain?"

Because the author of B does not know which class comes next in the MRO. For one object it may be C, for another subclass it may be something else. Positional arguments would depend on a fixed order that nobody controls. Keyword arguments let each class take the ones it knows and pass the rest on.

q35_chain.pyruns offline
D(b=1, c=2) -> 1 2
D(bb=1)     -> object.__init__() takes exactly one argument (the instance to initialize)

Each class writes def __init__(self, *, b=0, **kw) and calls super().__init__(**kw). The star makes b keyword-only, so D(1, 2) cannot put a number into the wrong slot. The extra **kw carries everything this class does not use.

The cost is that signatures become less self-documenting. I list the names in the docstring and keep the chain short.

"What happens at the end of the chain?"

The last cooperative class passes whatever remains to object.__init__. That method accepts no extra arguments, so it raises TypeError if anything is left. In the demo above, D(bb=1) failed with object.__init__() takes exactly one argument (the instance to initialize).

That is a feature. A mistyped keyword such as bb for b is caught at once, rather than silently ignored. Without the end-of-chain check, every **kw would swallow typos.

The wording of the message varies by version, so I do not match on it in tests; I catch TypeError.

A problem appears when a base class cannot cooperate: a third-party class whose __init__ does not call super().__init__(), or takes fixed positional arguments. Do not edit the library. Wrap it with a small adapter class that does cooperate, or put it last in the bases so nothing needs to come after it. If you control the whole chain, give a shared base class the job of absorbing leftovers, such as raising a clearer error than object does.

"What is the zero-argument super() doing?"

The compiler helps. When a function body contains the bare name super, the compiler gives the function a hidden variable called __class__, a closure cell holding the class where the method is defined. At call time, super() takes that class and the first argument (self) and behaves as super(__class__, self).

q35_cell.pyruns offline
('__class__',)
<class '__main__.Child'>
base

The cell holds Child, the class that owns the method. Starting from there, super() finds the next class after it in type(self).__mro__.

Two results follow. The zero-argument form works only inside a method defined in a class body, so it fails in a function you attach to a class later. And it is rename-safe, because the cell points at the class object and not at a name. A class decorator that builds a new class (such as dataclass(slots=True)) can break it in some versions, since the cell may still point at the old class.

"How do mixins fit in?"

A mixin is a small class that adds one behaviour and calls super() so the rest of the chain still runs. It is written to sit to the left of the main base: class Service(LoggingMixin, Base). Being first in the MRO, its method runs first, does its extra work, and then super() reaches Base.

Take a LoggingMixin.handle that logs, calls super().handle(req), and logs the result. Put it on any handler class and you get logging around every handle without editing the handler. Another mixin for metrics can be stacked in front of that one, and each wraps the next.

Rules I keep for mixins. They hold no state of their own, or only state with a clear name. They define no __init__, or follow the keyword-only pattern from the first question. They declare __slots__ = () if the main class uses slots (Q33). And they are named for what they add, so the reader knows what is safe to combine.

Q36. "What is a metaclass, and what does class Foo: ... do step by step?"

Reveal answer

Strong answer A metaclass is the class of a class. Ordinary objects are instances of classes; classes are themselves objects, and they are instances of a metaclass. The default metaclass is type, so type(Foo) is type.

The class Foo(Base): ... statement runs these steps. 1) Python picks the metaclass (from the metaclass= argument, or the bases, defaulting to type) and calls its __prepare__ to get an empty namespace dict. 2) It runs the class body as code inside that namespace, so every def and assignment lands in the dict. 3) It calls Meta(name, bases, namespace), which is Meta.__new__ then Meta.__init__. 4) Inside type.__new__, Python calls __set_name__ on every descriptor in the namespace, then Base.__init_subclass__. 5) After the class exists, any class decorators run, and the result is bound to the name Foo.

So class Foo: x = 1 is roughly Foo = type("Foo", (), {"x": 1}), which you can write by hand.

A custom metaclass lets you change step 3, for example to register classes, validate the body, or rewrite the namespace. Since 3.6, __init_subclass__ and __set_name__ cover most needs with far less machinery (Q37).

Picture it Every hook prints a line, so the order is visible.

The setup: A metaclass, a descriptor with __set_name__, a base with __init_subclass__ and a class decorator, all used by one class statement.

q36_class_creation.py · Python 3.14runs offline
class Meta(type):
    @classmethod
    def __prepare__(mcs, name, bases, **kw):
        print("Meta.__prepare__   -> empty namespace for", name)
        return {}
    def __new__(mcs, name, bases, ns, **kw):
        print("Meta.__new__       -> builds the class object", name)
        return super().__new__(mcs, name, bases, ns)
    def __init__(cls, name, bases, ns, **kw):
        print("Meta.__init__      -> class", name, "is initialised")
        super().__init__(name, bases, ns)

class Field:
    def __set_name__(self, owner, name):
        print(f"Field.__set_name__ -> attribute {name!r} of {owner.__name__}")

class Base:
    def __init_subclass__(cls, **kw):
        print("Base.__init_subclass__ ->", cls.__name__, "is a new subclass")
        super().__init_subclass__(**kw)

def decorate(cls):
    print("class decorator    -> runs last")
    return cls

@decorate
class Foo(Base, metaclass=Meta):
    print("class body runs    -> x and f are being defined")
    x = Field()
    def f(self):
        pass

print("type(Foo) is", type(Foo).__name__, "| type(Meta) is", type(Meta).__name__)
Bar = type("Bar", (Base,), {"y": 1})                   # the same machinery, by hand
print("Bar.y =", Bar.y)
output · Python 3.14runs offline
Meta.__prepare__   -> empty namespace for Foo
class body runs    -> x and f are being defined
Meta.__new__       -> builds the class object Foo
Field.__set_name__ -> attribute 'x' of Foo
Base.__init_subclass__ -> Foo is a new subclass
Meta.__init__      -> class Foo is initialised
class decorator    -> runs last
type(Foo) is Meta | type(Meta) is type
Base.__init_subclass__ -> Bar is a new subclass
Bar.y = 1

What you see: __prepare__ runs first, then the body, then __new__; inside __new__ come __set_name__ and __init_subclass__; then the metaclass __init__, and the decorator comes last. The hand-written type(...) call goes through the same hooks.

Why: a class is built by calling its metaclass with the name, bases and body namespace; the other hooks are steps inside that call.

Java · Spring

Classes come from the compiler.

Foo.javaruns offline
class Foo extends Base {
  int x;
}
// class loaded by ClassLoader;
// no code runs "as" class body

Python

The class statement is code.

foo.pyruns offline
class Foo(Base):
    x = 1
# runs the body, then calls
# type("Foo", (Base,), {...})

The shift: In Python a class is an object built at run time by calling a metaclass, which is why classes can be created, changed and registered by ordinary code.

Land it I describe a class statement as: prepare a namespace, run the body, call the metaclass, fire __set_name__ and __init_subclass__, apply decorators; and I reach for a metaclass only when those hooks are not enough.

Likely follow-ups
"When is a metaclass still justified?"

Use a metaclass when you must control how the class object itself is built, and no simpler hook can do it. Four real cases:

  1. ORMs: turn field declarations in the class body into columns and a table mapping before the class exists. SQLAlchemy's declarative base and Django models do this.
  2. abc.ABCMeta: tracks abstract methods and lets isinstance accept registered "virtual" subclasses.
  3. Enums: EnumType makes Color.RED a member with a name and value, and rejects duplicate names.
  4. Custom namespaces: a metaclass with __prepare__ can record or restrict what the body defines.

For registration, checking subclass attributes and passing class keywords, __init_subclass__ and __set_name__ are simpler and do not conflict with other libraries (Q37). My test before writing one: "can I do this with a class decorator or __init_subclass__?" If yes, I do that.

"What is a metaclass conflict?"

When a class has bases with different metaclasses, Python must pick one metaclass that is a subclass of all of them. If no such class exists, class creation fails at once with TypeError: metaclass conflict. It usually appears when you combine two frameworks, for example an ABC with an ORM base.

q36_meta.pyruns offline
metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
M2

Base uses my metaclass M, abc.ABC uses ABCMeta, and neither is a subclass of the other, so Both fails. The fix in the second half is a combined metaclass M2(M, abc.ABCMeta), passed with metaclass=M2.

That fix works, but you must write it, and it only exists once you know about the clash. For a library meant to be mixed with others, that is a good reason to use __init_subclass__ and never impose a metaclass on users.

"What is __new__ versus __init__ on an ordinary class?"

__new__ creates the instance. It is a static method that receives the class and returns a new object. __init__ then receives that finished object and sets up its fields. In a normal class you almost never need __new__.

You need it for types whose value is fixed at creation. A str, int, float or tuple subclass is immutable, so __init__ comes too late to change the value. For example, a Celsius(float) that rejects values below absolute zero, or that rounds, must do so in __new__ before float.__new__(cls, value) builds the object. Singletons and instance caches also use __new__, because it can return an existing object.

One detail catches people: if __new__ returns an instance of the class, Python then calls __init__ on it, possibly again on a cached object.

A metaclass has the same pair one level up. Meta.__new__(mcs, name, bases, namespace) builds the class object, and Meta.__init__ adjusts it afterwards. I put work that changes the namespace in __new__ and checks in __init__.

"Can I see __prepare__ doing something useful?"

The classic use was to give the class body a namespace that remembers order. Before Python 3.6, class bodies used a plain dictionary with no guaranteed order, so a metaclass for enums or database columns returned an OrderedDict from __prepare__ to keep the order of definition. Since 3.6, class bodies keep definition order by default, so that use is gone.

The remaining uses are about controlling the namespace itself. A __prepare__ can return a dictionary subclass that raises when a name is assigned twice, so two def total or two x = 1 in one body is an error rather than a silent overwrite. The standard enum module does this for duplicate member names. A DSL can also return a special mapping whose __missing__ or __getitem__ creates objects for unknown names.

It is a classmethod called before the body runs and receives the class name, the bases and the keywords. Outside enum-like designs and DSLs I have rarely needed it.

Q37 · Scenario. "Every subclass of Plugin must register itself automatically. Metaclass or __init_subclass__ — and why?"

Reveal answer

Strong answer __init_subclass__. It is a hook method on the parent class that Python calls once for every new subclass, right after the subclass is created. It gets the new class as its first argument, and any keyword arguments given in the class statement.

A registry then takes four lines: the parent keeps a dict and the hook adds cls to it. No metaclass is needed, and nothing about how classes are created changes, so there is no metaclass conflict when someone combines Plugin with ABC or an ORM base.

Stack choice. __init_subclass__: use by default for registration, validation of subclass attributes, and passing class keyword arguments. Metaclass: use only if you must change the class body before the class exists (rewrite attributes, control __prepare__) or customise class-level operations such as len(Cls). Class decorator: use if registration should be opt-in and visible at the class. Explicit register(cls) call or entry points: use if plugins come from other packages and must not depend on import side effects.

Remember the catch: registration happens when the module is imported. A plugin in a module nobody imports is never registered, so you need a discovery step (import a package, or use entry points).

Picture it A registry with __init_subclass__, and the metaclass conflict that the metaclass version causes.

The setup: Plugins register under a key given in the class statement; then the same base is combined with ABC through a metaclass version.

q37_plugin_registry.py · Python 3.14runs offline
from abc import ABC, ABCMeta

class Plugin:
    registry = {}
    def __init_subclass__(cls, key=None, **kw):
        super().__init_subclass__(**kw)
        Plugin.registry[key or cls.__name__.lower()] = cls

class CsvExport(Plugin, key="csv"):
    pass

class JsonExport(Plugin):                 # key defaults to class name
    pass

print("registry:", {k: v.__name__ for k, v in Plugin.registry.items()})

class Combined(Plugin, ABC):              # ✅ works: no custom metaclass involved
    pass
print("Combined registered as:", [k for k, v in Plugin.registry.items() if v is Combined])

class RegMeta(type):                      # the metaclass version
    registry = {}
    def __init__(cls, name, bases, ns):
        super().__init__(name, bases, ns)
        RegMeta.registry[name.lower()] = cls

class MPlugin(metaclass=RegMeta):
    pass

try:
    class Both(MPlugin, ABC):             # ❌ TRAP: two different metaclasses
        pass
except TypeError as e:
    print("metaclass version + ABC ->", e)
output · Python 3.14runs offline
registry: {'csv': 'CsvExport', 'jsonexport': 'JsonExport'}
Combined registered as: ['combined']
metaclass version + ABC -> metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases

What you see: both plugins register, with an explicit key and a default one; combining with ABC works; the metaclass version fails as soon as it meets another metaclass.

Why: __init_subclass__ is a normal method inherited by subclasses, so it composes with anything; metaclasses must be compatible with each other.

Java · Spring

Scan the classpath.

Registry.javaruns offline
// reflection or ServiceLoader
// finds implementations
for (var p : ServiceLoader
    .load(Plugin.class)) { ... }

Python

The base class hears about it.

registry.pyruns offline
class Plugin:
    registry = {}
    def __init_subclass__(cls, **kw):
        Plugin.registry[cls.__name__] = cls

The shift: Java discovers implementations by scanning; Python's class statement notifies the parent as it runs. See the registry idiom.

Land it I use __init_subclass__ for self-registration because it needs no metaclass, composes with ABC and ORMs, and I make sure plugin modules get imported.

Likely follow-ups
"What if the plugin module is never imported?"

Then the class statement never runs, so nothing registers. The registry is exactly as complete as your imports. This is the biggest weakness of import-time registration, and it shows up as "the plugin works in my test but not in production", where a different start-up path imports fewer modules.

  1. Import the package at start-up: walk the plugins folder with pkgutil.iter_modules and call importlib.import_module for each, so the discovery step is visible in one place.
  2. Use entry points: an installed package declares [project.entry-points."pricer.plugins"] in its metadata. The host calls importlib.metadata.entry_points(group="pricer.plugins") and loads each one. This finds plugins from other packages without importing them first.
  3. Check at start-up: assert that the expected keys are in the registry, so a missing plugin fails the boot rather than a customer.

I choose entry points when third parties write plugins, and a plain package import when all plugins live in my repository.

"How do I skip abstract intermediate classes?"

There are two ways. One is a class keyword. The hook receives the keywords from the class statement, so a parent can have def __init_subclass__(cls, register=True, **kw) and an intermediate class can say class Base2(Plugin, register=False). The hook returns early when register is false.

The other is to detect it. inspect.isabstract(cls) is true for a class that still has abstract methods, so a hook can skip those. The base must use ABC. I ran a check inside the hook: Mid(P), which adds nothing, reported abstract, and Leaf(P), which implements f, reported not abstract ({'Mid': True, 'Leaf': False}, same on 3.12 and 3.14). That order of events is an implementation detail of ABCMeta, so re-check it on your version before depending on it.

I prefer the keyword, because it is explicit and appears in the subclass's own header. A reader sees "this class is not a plugin" right where it is declared. The abstract-method test is a good extra guard, not the main switch.

"Can __init_subclass__ validate subclasses?"

Yes, and it is one of its best uses. The hook runs once, when each subclass is created, so a check there raises at import time, at the exact class statement that is wrong. The developer sees the error on the first run instead of during a customer request.

q37_validate.pyruns offline
registry: ['csv']
Bad must define key

Csv declares a key and registers. Mid opts out with register=False. Bad forgets the key and fails with a clear message that names the class.

Things I check in this hook: required attributes exist and have the right type, keys are unique (raise on a duplicate registration), and method signatures match the contract. Call super().__init_subclass__(**kw) so cooperating mixins still work.

The guarantee is the same as a metaclass would give, with no metaclass, so no conflict with ABCs or ORMs.

"Is a class decorator better sometimes?"

Sometimes. A class decorator such as @register("csv") above the class makes registration visible and opt-in, and it uses no inheritance at all. A reader sees at the class that it is a plugin, and the name can come from the decorator argument instead of a class attribute.

Its weakness is the mirror image of its strength. If someone forgets the decorator, the class silently stays out of the registry, and no code notices. __init_subclass__ cannot be forgotten, because inheriting is the registration.

My rule is about what the domain says. If "every subclass of Plugin is a plugin", the rule belongs in the parent, so I use __init_subclass__. If plugins are a subset of the classes, or the class does not inherit from a common base, so you cannot add a hook, use a decorator.

And if registration must work for code that is not yours, an explicit register(cls) call or entry points are the honest answer. I also add a test that lists the registry, so a missing registration is a failing test.

Q38. "dataclass, NamedTuple, attrs or Pydantic model — when do you use each?"

Reveal answer

Strong answer Decide by two questions: does the data come from outside the program (needs validation and parsing), and does it need to be a tuple or immutable?

dataclass (standard library): plain Python objects with generated __init__, __repr__, __eq__, optional frozen, slots, order. No validation. Use for internal domain objects whose data you already trust. NamedTuple: an immutable tuple with named fields; unpacks, indexes, hashes, is tiny and fast to create. Use for small, fixed, read-only records and multiple return values.

attrs: a third-party superset of dataclasses with validators, converters, richer options, and it predates dataclasses. Use if you need its extra features or support older code. Pydantic: validates and converts data on creation, parses JSON, produces schemas. Use at the boundary where untrusted data enters: HTTP bodies, config files, messages.

A common architecture: Pydantic models at the edges, dataclasses (or plain classes) inside, so the check runs once and the core stays fast and simple. Pydantic costs more per object, because it validates every field.

TypedDict is another option for describing the shape of a dict that you pass around unchanged (Q119).

Picture it The same order record in four shapes, what each does with bad input, and the cost to create one.

The setup: One record id: int, qty: int built from a good value and from the string "3".

q38_record_types.py · Python 3.12runs offline
import timeit
from dataclasses import dataclass
from typing import NamedTuple
import attrs
from pydantic import BaseModel, ValidationError

@dataclass(frozen=True, slots=True)
class DC:
    id: int
    qty: int

class NT(NamedTuple):
    id: int
    qty: int

@attrs.define(frozen=True)
class AT:
    id: int = attrs.field(validator=attrs.validators.instance_of(int))
    qty: int = attrs.field(converter=int)

class PM(BaseModel):
    id: int
    qty: int

print("dataclass with qty='3':", DC(1, "3"))
print("namedtuple with qty='3':", NT(1, "3"))
print("attrs      with qty='3':", AT(1, "3"), "(converter)")
print("pydantic   with qty='3':", PM(id=1, qty="3"), "(coerced)")
for label, make in (("dataclass", lambda: DC(1, "x")), ("attrs", lambda: AT(1, "x")), ("pydantic", lambda: PM(id=1, qty="x"))):
    try:
        make()
        print(f"{label:9} with qty='x': accepted")
    except (ValueError, ValidationError) as e:
        print(f"{label:9} with qty='x': rejected ->", str(e).splitlines()[0])

for label, make in (("dataclass", lambda: DC(1, 3)), ("NamedTuple", lambda: NT(1, 3)),
                    ("attrs", lambda: AT(1, 3)), ("pydantic", lambda: PM(id=1, qty=3))):
    t = timeit.timeit(make, number=200_000) / 200_000
    print(f"create {label:10}: {t * 1e9:6.0f} ns each")
output · Python 3.12runs offline
dataclass with qty='3': DC(id=1, qty='3')
namedtuple with qty='3': NT(id=1, qty='3')
attrs      with qty='3': AT(id=1, qty=3) (converter)
pydantic   with qty='3': id=1 qty=3 (coerced)
dataclass with qty='x': accepted
attrs     with qty='x': rejected -> invalid literal for int() with base 10: 'x'
pydantic  with qty='x': rejected -> 1 validation error for PM
create dataclass :    417 ns each
create NamedTuple:    268 ns each
create attrs     :    545 ns each
create pydantic  :    903 ns each
# Python 3.12 venv, pydantic 2.13, attrs 26.1; timings measured on the course machine

What you see: the dataclass and the NamedTuple accept the string "3" unchecked, attrs converts it, Pydantic coerces it and rejects "x"; creation costs 268 ns for the NamedTuple, 417 ns for the dataclass and 545 ns for attrs, and about 900 ns for Pydantic, which does the most work.

Why: validation is work done on every object, so the right place for it is where untrusted data enters, not on every internal object.

Plain

Trust the caller, stay fast.

inner.pyruns offline
@dataclass(frozen=True, slots=True)
class Order:
    id: int
    qty: int

Boundary

Validate untrusted input once.

edge.pyruns offline
class OrderIn(BaseModel):
    id: int
    qty: int = Field(gt=0)
# parse JSON -> OrderIn -> Order

The shift: Validate at the boundary with Pydantic, then pass plain, fast objects through the core.

Land it I use Pydantic at the boundary where data is untrusted, frozen slotted dataclasses for internal values, NamedTuple for tiny read-only records, and attrs when I need its extra features.

Likely follow-ups
"Why not Pydantic everywhere?"

Because validation costs time and, inside your own code, it checks things that are already true. Pydantic validates and coerces every field when an object is created. That is exactly what you want where data enters the program, and wasted work for an object built from values you have just checked. The page's timing shows about 900 ns for a Pydantic object against about 417 ns for a plain dataclass.

Work out what that means for you. At one million objects, that is roughly 0.9 s against 0.42 s, a half-second difference. For a web request that creates a handful of objects, nobody can notice it. In a loop that builds ten million rows, it is five seconds.

There is also a design reason. Using Pydantic for every internal object ties your core logic to a framework. Dataclasses are standard and easy to read. My architecture is Pydantic at the edges, where data is untrusted, and dataclasses inside, so each value is checked once.

"When do I pick attrs over dataclass?"

When I need features the standard library does not have, or I am in a codebase that already uses it. attrs offers per-field validators and converters, on_setattr hooks that validate on later assignments, and more control over equality, hashing and the repr. It also has the modern attrs.define style, and it predates dataclasses, which borrowed its design (PEP 557 credits it). It is mature and widely used; pytest's internals and many large libraries rely on it.

The standard dataclass has hooks too, but fewer: __post_init__ and field() options. If you want "convert this string to an int when the field is set" and "check this on every assignment", attrs does it in a line, while a dataclass needs a property or extra code.

For new code without those needs, I choose the dataclass. It adds no dependency, every Python developer can read it, and tools understand it. I switch to attrs when I find myself rewriting its features by hand.

"What is the difference between NamedTuple and a frozen dataclass?"

A NamedTuple is a tuple, with all the consequences. It unpacks, it is indexable, and it compares equal to a plain tuple or to any other NamedTuple with the same values. A frozen dataclass is a distinct type that compares only with its own class.

q38_nt.pyruns offline
NamedTuple Point == Offset  : True
NamedTuple Point == (1, 2)  : True
dataclass P2 == O2           : False
dataclass P2 == (1, 2)      : False

That equality can be a bug. A Point(1, 2) equals an Offset(1, 2), so a dictionary or set could mix them up, and nothing warns you. It can be a feature when the record must be interchangeable with plain tuples, such as a row from csv or a return value you unpack.

Defaults, methods, slots, ordering control and per-field options are easier with a dataclass. NamedTuples are slightly smaller and faster to create. I choose the dataclass by default, and a NamedTuple when I want tuple behaviour, such as unpacking a multiple return value.

"How do I convert between them?"

Each tool has a way out to a dictionary and a way back in. The conversions belong in one place, so the layering stays visible.

  1. To a dict: dataclasses.asdict(obj), obj._asdict() for a NamedTuple, attrs.asdict(obj), and model.model_dump() for Pydantic.
  2. From a dict: Cls(**data) for dataclasses and attrs, Point(**data) for NamedTuple, and Model.model_validate(data) for Pydantic, which also checks the types.
  3. From an object: Pydantic can read attributes with model_validate(obj, from_attributes=True), which is how you turn a database row or a dataclass into a response model.

Be aware that asdict copies nested dataclasses recursively, which can be slow on big structures, and that model_dump() needs mode="json" when you want types such as datetime turned into strings.

I put these conversions in one adapter or mapper module. Then the rest of the code never has to know which model type is on the other side of a boundary.

Q39 · Scenario. "A @dataclass with a list default raises ValueError at import time. Why, and what is the fix?"

Reveal answer

Strong answer A default value in a dataclass is stored once on the class and handed to every instance that does not supply its own. A list written as items: list = [] would therefore be one list shared by every instance, which is the mutable default bug from Q3 in class form.

Python's dataclass decorator refuses it at class-creation time: ValueError: mutable default <class 'list'> for field items is not allowed: use default_factory. Since 3.11 the check covers any unhashable default (list, dict, set and also custom unhashable classes); earlier versions checked only those three types.

The fix is field(default_factory=list). default_factory is a function called once per instance to create a fresh default. Use it for anything mutable, or for a value that must be computed per object, such as default_factory=dict, default_factory=datetime.now, default_factory=lambda: uuid4().hex.

The error appears at import time, which is good news: the bug is caught on the first run, not by a customer. Plain classes have no such guard, which is why a def __init__(self, items=[]) slips through.

Picture it The error, the fix, and two instances proving they no longer share.

The setup: An order with a list of discount codes, first with a mutable default and then with a factory.

q39_dataclass_default.py · Python 3.14runs offline
from dataclasses import dataclass, field

try:
    @dataclass
    class BadOrder:
        codes: list = []                       # ❌ TRAP
except ValueError as e:
    print("ValueError:", e)

@dataclass
class Order:
    id: int
    codes: list[str] = field(default_factory=list)      # ✅ new list per instance

a, b = Order(1), Order(2)
a.codes.append("FIRST50")
print("a:", a)
print("b:", b, "| shared list:", a.codes is b.codes)

class PlainOrder:
    def __init__(self, id, codes=[]):                    # a plain class does not stop you
        self.id, self.codes = id, codes
p, q = PlainOrder(1), PlainOrder(2)
p.codes.append("FIRST50")
print("plain class, q.codes =", q.codes, "<- leaked")
output · Python 3.14runs offline
ValueError: mutable default <class 'list'> for field codes is not allowed: use default_factory
a: Order(id=1, codes=['FIRST50'])
b: Order(id=2, codes=[]) | shared list: False
plain class, q.codes = ['FIRST50'] <- leaked

What you see: the decorator raises at class creation; with a factory, b stays empty; the plain class leaks the code into q.

Why: the dataclass decorator inspects defaults and rejects unhashable ones, because it knows they would be shared.

Plain class

No guard rail.

plain.pyruns offline
def __init__(self, codes=[]):
    self.codes = codes
# silent shared state

dataclass

Refused at import.

dc.pyruns offline
codes: list = field(
    default_factory=list)
# fresh list per instance

The shift: The dataclass turns a silent runtime bug into an immediate import error with the fix in the message.

Land it I explain that a class-level default is shared, that dataclass rejects mutable defaults, and I use field(default_factory=...) so each instance gets its own.

Likely follow-ups
"Why does the check look at hashability?"

Because a hashable default is, in practice, one you cannot change in place, such as a number, string or tuple, so sharing it between instances is harmless. An unhashable object is usually mutable, which is where the shared-state bug lives. Since Python 3.11 the check is default.__class__.__hash__ is None. It rejects lists, dicts and sets, and also any class of yours that defines __eq__ without __hash__, because Python then sets __hash__ to None (Q22).

q39_defaults.pyruns offline
Box.__hash__ -> None
mutable default <class '__main__.Box'> for field b is not allowed: use default_factory

The check is a heuristic. A hashable object that is mutable, for example a class that keeps the default object.__hash__ and has changeable fields, passes it, and the sharing bug is still there. So the practical rule remains: for any default that is not a plain constant, use default_factory.

"How do I give a field a default that depends on another field?"

Use __post_init__, which the generated __init__ calls after the fields are set. Mark the derived field field(init=False) so it is not an argument of the constructor, and compute it there.

cart.pyruns offline
@dataclass
class Cart:
    items: list[float] = field(default_factory=list)
    total: float = field(init=False)

    def __post_init__(self):
        self.total = sum(self.items)

This works because a field with init=False is left out of the constructor, so it may follow fields that have defaults. With frozen=True, a plain assignment inside __post_init__ raises, so write object.__setattr__(self, "total", ...) as in Q10, or avoid storing the value and offer a @property instead.

A derived value that is stored can go stale if a field changes later. For a mutable class I prefer a property. For a frozen class, storing it once is safe, since nothing can change. A default_factory cannot see other fields, which is why this hook exists.

"What does field(default_factory=...) do for frozen or slots classes?"

It works the same way. default_factory is called inside the generated __init__ each time an instance is created, whatever the class options are. So frozen=True and slots=True do not change how you write it: items: list = field(default_factory=list) in both.

Plain defaults differ with slots. A slot name cannot also be a class attribute holding a default, so with slots=True the dataclass decorator builds a new class, removes the class-level defaults, and fills them in inside __init__. You never see this, but it is why @dataclass(slots=True) creates a new class object and not the one you wrote. That detail can affect zero-argument super() and any code that kept a reference to the original class (Q35).

For a frozen class, the factory result is stored once and cannot be replaced, but a list inside it can still be changed with append. Frozen means the attribute cannot be rebound. For real immutability, use a tuple or frozenset field.

"How does Pydantic differ?"

Pydantic copies a mutable default for each instance, so items: list = [] is safe in a Pydantic model. The author chose convenience, and that is deliberate, since Pydantic validates and copies data on creation anyway.

The inconsistency is the danger. A developer who learns that "lists are fine" in Pydantic models carries the habit to a dataclass, or to a plain function default (Q3), where it is a bug. The dataclass at least fails loudly at import. A plain def f(items=[]) does not.

So I write Field(default_factory=list) in Pydantic and field(default_factory=list) in dataclasses, which is one habit that is correct everywhere. The few extra characters are cheap, and a reviewer can check the pattern at a glance.

I make an exception only for immutable defaults (numbers, strings, None, tuples), where a plain value is right in every framework.

Q40 · Design. "Design a validated field (type plus range) that 20 model classes can reuse."

Reveal answer

Strong answer A descriptor, because it is the one tool that lets a single piece of code intercept both reading and writing of an attribute on many classes (Q32). Each field is declared once as a class attribute, for example qty = Ranged(int, 1, 1000).

Design: the descriptor stores its value in the instance under a private name learned from __set_name__. __set__ checks the type and the range and raises a clear TypeError or ValueError that names the class and field. __get__ returns the stored value, or the descriptor itself when accessed on the class, so documentation tools still work.

Things I add: a shared base class so Positive, Percentage and NonEmpty are one-liners; support for default values; a way to disable the check for trusted bulk loads; a test per descriptor, not per model.

Alternatives and when to switch: Pydantic if the models are parsed from JSON anyway and you want a ready-made Field(ge=1, le=1000). attrs validators or dataclass __post_init__ if you have few classes. A property if only one class needs it. A descriptor is the answer when the same rule repeats across many plain classes and you do not want a framework.

Picture it A reusable Ranged field used by three classes, and the errors it raises.

The setup: One descriptor class, used on Order, Product and Coupon.

q40_validated_field.py · Python 3.14runs offline
class Ranged:
    def __init__(self, kind, low=None, high=None):
        self.kind, self.low, self.high = kind, low, high

    def __set_name__(self, owner, name):
        self.label = f"{owner.__name__}.{name}"
        self.slot = "_" + name                       # where the value is stored

    def __get__(self, obj, owner=None):
        return self if obj is None else getattr(obj, self.slot)

    def __set__(self, obj, value):
        if not isinstance(value, self.kind) or isinstance(value, bool):
            raise TypeError(f"{self.label} must be {self.kind.__name__}, got {type(value).__name__}")
        if self.low is not None and value < self.low:
            raise ValueError(f"{self.label} must be >= {self.low}, got {value}")
        if self.high is not None and value > self.high:
            raise ValueError(f"{self.label} must be <= {self.high}, got {value}")
        setattr(obj, self.slot, value)

class Order:
    qty = Ranged(int, 1, 1000)
    def __init__(self, qty):
        self.qty = qty

class Product:
    qty = Ranged(int, 0)
    price = Ranged(float, 0.0)
    def __init__(self, qty, price):
        self.qty, self.price = qty, price

class Coupon:
    percent = Ranged(int, 1, 100)
    def __init__(self, percent):
        self.percent = percent

print(Order(5).qty, Product(3, 9.5).price, Coupon(50).percent)
for label, make in (("qty = -5", lambda: Order(-5)), ("qty = '3'", lambda: Order("3")),
                    ("price = -1.0", lambda: Product(1, -1.0)), ("percent = 101", lambda: Coupon(101)),
                    ("qty = True", lambda: Order(True))):
    try:
        make()
    except (TypeError, ValueError) as e:
        print(f"{label:14}->", e)
o = Order(5)
o.qty = 10
print("reassign ok:", o.qty)
try:
    o.qty = 5000
except ValueError as e:
    print("reassign bad ->", e)
output · Python 3.14runs offline
5 9.5 50
qty = -5      -> Order.qty must be >= 1, got -5
qty = '3'     -> Order.qty must be int, got str
price = -1.0  -> Product.price must be >= 0.0, got -1.0
percent = 101 -> Coupon.percent must be <= 100, got 101
qty = True    -> Order.qty must be int, got bool
reassign ok: 10
reassign bad -> Order.qty must be <= 1000, got 5000

What you see: the same descriptor guards three classes with different limits, error messages name the class and field, and the check also runs on later assignment, not only in __init__.

Why: __set_name__ hands the descriptor its owner and attribute name, so one object can serve every class that declares it.

Repeated by hand

A property per field per class.

props.pyruns offline
@property
def qty(self): return self._q
@qty.setter
def qty(self, v):
    if v < 1: raise ValueError
    self._q = v

One descriptor

Declare the rule once.

desc.pyruns offline
class Order:
    qty = Ranged(int, 1, 1000)
class Product:
    qty = Ranged(int, 0)
# rule lives in one class

The shift: A descriptor turns a repeated validation snippet into a single reusable declaration. See the descriptor idiom.

Land it I write a Ranged descriptor with __set_name__, __get__ and __set__ that checks type and range with clear errors, and use Pydantic instead when the data is parsed from JSON anyway.

Likely follow-ups
"Does the descriptor work with __slots__?"

Not as written. The descriptor stores its value in the instance as _qty through setattr or obj.__dict__. A slotted class has no __dict__, and a name that is not declared in __slots__ raises AttributeError.

  1. Add the private name to the slots: __slots__ = ("_qty",), and the descriptor works. This is simple and fast, but each model must list its private names.
  2. Keep values inside the descriptor: a WeakKeyDictionary keyed by the instance. It needs no slot, but requires "__weakref__" in the slots, hides state away from the object, and breaks copy and pickle.

I choose the first. State that lives in the object is visible in repr and survives copying and pickling, and the per-model cost is one line. A name clash is another trap: a slot called qty cannot also be the descriptor. That is why the stored name has a leading underscore.

"Why return self when obj is None?"

When you access Order.qty on the class, Python calls __get__(None, Order), so obj is None. If the method ran its normal path, it would try to read the stored value from None and crash with an AttributeError.

Returning the descriptor itself in that case has real uses. You can inspect the rule, as in Order.qty.high or Order.qty.low, which a form generator or documentation tool can read. help(Order) and inspect do not crash. And a test can check that a model declares the right limits without creating an object.

The line is two words: if obj is None: return self. It follows the convention of property, which returns the property object when read from the class, and of functions, which return themselves.

The one exception is a descriptor made to be a class-level value, such as a lazy class property. There, returning a computed result for obj=None is the point.

"How do I test it?"

Test the descriptor class once, thoroughly, using a tiny model class defined inside the test. Each model then needs only a light test that it declares the field with the right limits.

  1. Good values: a normal value, and exact boundaries equal to low and high, which are the usual off-by-one spots.
  2. Bad values: one below the low bound, one above the high bound, and a wrong type such as "5" or 5.0 for an int field.
  3. Edge types: True for an int field. In Python bool is a subclass of int, so an isinstance check accepts it unless you reject it explicitly.
  4. Messages: assert that the error text names the class and the field, because that is what a developer reads in a log.

I also test that two instances keep separate values, since a descriptor that stores on itself, and not on the instance, shares one value across all instances. It is a classic bug.

"What about validation on bulk loading, where speed matters?"

Each assignment runs Python code, which costs about a microsecond for a check like this. Take 3 million rows with 5 validated fields each. At 1 microsecond per check, that is 15 million checks, about 15 seconds of validation (assuming that figure; measure yours). For a batch job that matters, and for a request handler it does not.

The structural answer is to validate where the data enters, and not on every assignment. Check the whole batch with a vectorised test (NumPy or pandas can compare a column to low and high in one call), or at the edge with Pydantic, whose core is compiled. Then build the objects through a fast path that skips the descriptor, such as a classmethod that fills the private names with object.__setattr__ or sets _qty directly.

Keep that bypass explicit and private, with a name such as _from_trusted, and use it only in the loader. Public construction should still validate. Otherwise the fast path is one careless call away from letting bad data in.

09 · DrillFunctions, Generators & the Execution Model — Q41–Q80

The second forty questions cover what senior Python interviews ask after the object model: how scopes, closures, decorators and generators work, what CPython does between python app.py and your first line, and what the GIL really protects. The answers lean on small programs that were actually run, with the timings measured on the course machine. Say yours first, then reveal.

Drill · Scope, closures and decorators

These questions test whether you can explain name resolution at compile time, the cell that a closure holds, and a decorator as plain code that runs once at definition time.

Q41. "Explain LEGB, and the UnboundLocalError you get from x += 1 inside a function."

Reveal answer

The real test Whether you know the decision about local versus global is made at compile time, for the whole function body.

Strong answer LEGB is the order Python searches for a name: Local (the current function), Enclosing (outer functions, for nested ones), Global (the module), Built-in (len, print and the rest). The first scope that has the name wins.

The subtle part is when the decision is made. Python decides whether a name is local when it compiles the function, not when it runs: if the name is assigned anywhere in the body (x = ..., x += 1, for x in, import x), it is local for the entire body.

So in def bump(): x += 1, the += makes x local from the first line. Executing x += 1 reads x first, but the local x has no value yet, so Python raises UnboundLocalError: cannot access local variable 'x' where it is not associated with a value. It does not fall back to the global.

The fixes: pass the value in and return the result (best), declare global x or nonlocal x if you truly mean the outer one (Q42), or use a mutable container or object owned by the outer scope.

Picture it The error, the compiler's decision as bytecode, and the four scopes.

The setup: A module-level x, a function that only reads it, and one that does x += 1.

q41_legb.py · Python 3.14runs offline
import dis

x = 10
def read():
    return x                       # no assignment -> global lookup

def bump():
    x += 1                         # ❌ TRAP: assignment makes x local everywhere in bump
    return x

print("read():", read())
try:
    bump()
except UnboundLocalError as e:
    print("bump() ->", e)
print("locals of read():", read.__code__.co_varnames, "| locals of bump():", bump.__code__.co_varnames)

print("--- bump() bytecode, first lines")
for line in dis.Bytecode(bump):
    print(f"  {line.opname:18}{line.argrepr}")
    if line.opname == "STORE_FAST":
        break

def outer():
    level = "enclosing"
    def inner():
        print("  inner sees:", level, "|", len("built-in len works"), "|", x)
    inner()
outer()
output · Python 3.14runs offline
read(): 10
bump() -> cannot access local variable 'x' where it is not associated with a value
locals of read(): () | locals of bump(): ('x',)
--- bump() bytecode, first lines
  RESUME            
  LOAD_FAST_CHECK   x
  LOAD_SMALL_INT    
  BINARY_OP         +=
  STORE_FAST        x
  inner sees: enclosing | 18 | 10

What you see: read() works because it never assigns x. bump() fails, and co_varnames lists x as a local of bump only. The bytecode starts with LOAD_FAST_CHECK on x (3.14's name for a read from a local slot that must be checked for emptiness), which is the read that fails.

Why: the compiler scans the whole function body for assignments before generating any code, so there is no way for line 1 to look at the global.

Java · Spring

Field or local, always spelled out.

Counter.javaruns offline
class Counter {
  int x = 10;
  void bump() { x += 1; }
}
// x is a field: explicit

Python

Assignment decides the scope.

counter.pyruns offline
x = 10
def bump():
    x += 1
# UnboundLocalError:
# x is local in bump

The shift: Python has no variable declarations, so assignment is the declaration, and it makes the name local for the entire function.

Land it I say LEGB is the search order, and x += 1 fails because any assignment makes x local for the whole function at compile time, so the read happens before the local has a value.

Likely follow-ups
"Why not let Python fall back to the global?"

Because then one line would mean two different things depending on the run. If x += 1 read the global x when no local existed and created a local after that, the same name would switch scope in the middle of a function. Nobody could say which x a line means.

Deciding at compile time fixes that. The compiler scans the whole function body, notes every name that is assigned, and makes those names local for the whole body. A local is then a numbered slot in a small array, and the bytecode is a fast LOAD_FAST with an index, with no dictionary lookup by name.

The price is that Python has no declarations. Assignment alone decides scope, which is why you need global and nonlocal (Q42) when you do want to rebind an outer name. The error is also a gift in disguise: UnboundLocalError tells you exactly that the name is local here, and nothing has set it yet.

"Do loops and if blocks create a scope?"

No. Python has function, class and module scopes, and comprehensions in Python 3 have their own scope for the loop variable. It has no block scope for for, while, if, with or try. A loop variable stays alive after the loop, and a name assigned inside an if exists after it if that branch ran.

q41_scopes.pyruns offline
loop variable after loop: 2
comprehension leaks j?  : False

The loop variable i survives (the value is 2), but the comprehension variable j did not leak into the module. Since Python 3.12 (PEP 709) comprehensions are inlined for speed, but the loop variable is still kept isolated.

Two bug patterns follow. A name set only inside a branch gives UnboundLocalError when the branch did not run. And a loop variable reused later holds the last value, so after for t in tenants the name t still points to the final tenant. That is also how late binding in Q43 works. I initialise names before the branch.

"What about class bodies?"

A class body is its own scope while it runs, but methods do not see it. A name used inside a method looks in Local, Enclosing functions, Global and Built-in, and skips the class. So a bare x in a method cannot find a class attribute x. You must write self.x or ClassName.x.

The reason is that a method is a function, and a class body is not an enclosing function. Class-level names live in the class dictionary, found by attribute lookup, and not by scope lookup.

In my test, a method returning a bare x, with x = 5 in the class, failed with NameError: name 'x' is not defined.

It surprises people from Java, where a field is visible by its bare name inside methods. When I need a constant inside a method, I write self.RATE or Pricer.RATE.

"How does built-in shadowing bite?"

Shadowing means your name hides a built-in one. Global comes before Built-in in LEGB, so after list = [1, 2] at module level, every later list(...) in that module finds your variable and fails.

q41_scopes.pyruns offline
list(...) after list=[..]: 'list' object is not callable

The failure often appears far from the cause. The assignment may be at the top of a long file, or inside a loop (for id in ids), and the error appears later when another function calls id(x) or max(...).

The usual victims are list, dict, set, str, id, type, input, max, min, sum, filter and format. Linters catch this: Ruff has rules A001 and A002 for variables and arguments that shadow built-ins. My habit is to name things items, order_id or kind rather than list, id and type.

Q42. "global versus nonlocal — when do you need each, and when is needing them a smell?"

Reveal answer

Strong answer Both statements say "this assigned name is not local". global x binds x to the module-level variable, so an assignment inside the function changes the global. nonlocal x binds x to the nearest enclosing function scope (not the module), so a nested function can rebind an outer function's variable.

You need them only for rebinding. Reading an outer name needs no declaration, and mutating an outer object (items.append(1)) needs none either, because that does not assign the name. You need global or nonlocal for count += 1 or state = new_value.

When is it a smell? global is almost always a smell in application code: hidden shared state, hard to test, unsafe with threads. Use a parameter and a return value, an object that owns the state, or a settings object. nonlocal is fine for small closures, such as a counter or a memoiser, but if a closure carries more than one or two pieces of state, a class is clearer.

Use global legitimately for simple module-level singletons initialised lazily, with care, and in small scripts.

Picture it A counter built three ways, and what global does to testability.

The setup: A global counter, a closure with nonlocal, and a class.

q42_global_nonlocal.py · Python 3.14runs offline
calls = 0
def tick_global():
    global calls                       # needed: we rebind the module-level name
    calls += 1
    return calls

def make_counter():
    n = 0
    def tick():
        nonlocal n                     # needed: we rebind the enclosing function's name
        n += 1
        return n
    return tick

class Counter:
    def __init__(self):
        self.n = 0
    def tick(self):
        self.n += 1                    # attribute rebinding: no declaration needed
        return self.n

a, b = make_counter(), make_counter()
print("closures are independent:", a(), a(), b())
c = Counter()
print("class instance          :", c.tick(), c.tick())
print("global                  :", tick_global(), tick_global())
print("global shared by whole module, current value:", calls)

items = []
def add(x):
    items.append(x)                    # mutation, no declaration needed
add(1)
print("mutated without global:", items)
output · Python 3.14runs offline
closures are independent: 1 2 1
class instance          : 1 2
global                  : 1 2
global shared by whole module, current value: 2
mutated without global: [1]

What you see: each closure keeps its own count, the class keeps it on the instance, and the global is one number for the whole module. The list example needed no declaration because it mutates and never assigns the name items.

Why: the declarations exist only to tell the compiler "this assignment targets an outer name".

Land it I use nonlocal for tiny closures, a class once state grows, and I treat global as a design smell because it is hidden shared state that breaks tests and threads.

Likely follow-ups
"Why is global state a problem for tests?"

Global state makes tests depend on each other. A test that changes a module-level variable leaves it changed for the next test, so results depend on order. You get tests that pass alone and fail together, or pass on your laptop and fail in CI where the order differs (Q139).

Say a function bumps a module-level calls = 0. Test A calls it twice, and test B asserts the counter is 1. Run alone, B passes. Run after A, it fails. Resetting the global in every test works until someone forgets once.

Passing state in as a parameter, or using an object that owns the state, removes the problem. Each test builds its own fresh object, so there is nothing to clean up, and tests can run in any order or in parallel.

When I must keep a module-level singleton, such as a settings object, I add a pytest fixture that resets it, and I use monkeypatch so that changes are undone automatically after each test.

"What does global have to do with threads?"

The line calls += 1 looks like one step but is three: read the value, add one, write it back. Another thread can run between those steps, and then one of the two updates is lost. The shared variable is the root problem.

This chapter measured it with four threads adding to one counter one million times each. On Python 3.14 with the GIL, the counter came out right in normal runs, because the interpreter rarely switches threads at exactly that spot. That is luck of timing, not a guarantee. On the free-threaded build 3.14t, about 2.7 to 2.9 million of the 4 million updates were lost (Q78). So code that "works" can break when you change the build or the Python version.

The fix is to protect the update with a threading.Lock, or to avoid shared state. A lock is the clear, portable fix. Better still, give each thread its own counter and add them after the threads join.

"What is nonlocal rejecting if I mistype?"

It refuses to create a name. nonlocal n tells Python that n belongs to an enclosing function, and the compiler checks that such a name exists. If it does not, the code does not even compile.

q42_nonlocal.pyruns offline
no binding for nonlocal 'n' found
1

The first line is the error message, and the second is global creating a variable at the module level, with no complaint. That makes typos loud for nonlocal and silent for global: if you write global totl and assign it, you now have a new module variable totl next to the original total, and no error until much later.

The check also means nonlocal cannot reach the module level. It looks only at enclosing function scopes. For module-level variables, you need global.

The error is raised at compile time, when the module is imported, so it appears at start-up and not in the middle of a request. I count that as a point in nonlocal's favour.

"What do you use instead of module-level mutable state?"

Move the state into an object with a clear owner and pass that object to the code that needs it.

  1. Mutable state: a small class or dataclass, built at start-up and passed to functions or injected into a constructor. A web framework's dependency injection does the same for you.
  2. Configuration: a frozen settings object, created once at start-up and read everywhere. Nobody can rebind it, so nobody can surprise anyone else.
  3. Caches: functools.cache on a pure function, or a cache object passed in, so it can be sized, cleared and replaced in tests.
  4. Counters and metrics: a metrics object, or a library such as prometheus_client, rather than a global integer.

A module-level constant is fine: TAX_RATE = 0.2 read by many functions never changes. The smell is a module-level variable that functions rebind with global.

The test I apply is simple. If I can create two independent copies of the thing in a test, it is not global state.

Q43 · Scenario. "Handlers registered in a loop all act on the last tenant. Explain late binding and give two fixes."

Reveal answer

Strong answer A closure captures the variable, not its value at that moment. All three lambdas in for t in tenants: handlers.append(lambda: reprice(t)) hold a reference to the same cell for t. The loop finishes before any handler runs, t then holds the last tenant, and every handler reads that. This is late binding: the name is looked up when the function runs, not when it is defined.

In the pricer incident that meant one tenant out of forty repriced forty times and the other thirty-nine not at all for a night.

Fix 1: bind the value at definition time with a default argument. lambda t=t: reprice(t) evaluates t when the lambda is created and stores it as that function's own default. Fix 2: functools.partial(reprice, t), which stores the value inside the partial object. A third fix is a factory function (def make(t): return lambda: reprice(t)), where each call creates a fresh scope with its own t.

Prefer partial or the factory: they cannot be broken by a caller passing an extra argument, as the default-argument trick can.

Picture it Three lambdas all printing the last tenant, then the two fixes.

The setup: Three tenants, handlers made in a loop, and the contents of the closure cell.

q43_late_binding.py · Python 3.14runs offline
from functools import partial

def reprice(tenant):
    return f"repriced {tenant}"

tenants = ["acme", "bolt", "cruz"]

def schedule(tenants):                              # the scheduler registers handlers in a function
    handlers = []
    for t in tenants:
        handlers.append(lambda: reprice(t))         # ❌ TRAP: captures the variable t
    return handlers

bad = schedule(tenants)
print("bad     :", [h() for h in bad])
print("one shared cell:", bad[0].__closure__[0] is bad[2].__closure__[0],
      "| cell holds:", bad[0].__closure__[0].cell_contents)

default_arg = [lambda t=t: reprice(t) for t in tenants]       # ✅ value bound as default
print("default :", [h() for h in default_arg])

with_partial = [partial(reprice, t) for t in tenants]         # ✅ value stored in partial
print("partial :", [h() for h in with_partial])

def make(t):                                                   # ✅ one fresh scope per call
    return lambda: reprice(t)
factory = [make(t) for t in tenants]
print("factory :", [h() for h in factory])
output · Python 3.14runs offline
bad     : ['repriced cruz', 'repriced cruz', 'repriced cruz']
one shared cell: True | cell holds: cruz
default : ['repriced acme', 'repriced bolt', 'repriced cruz']
partial : ['repriced acme', 'repriced bolt', 'repriced cruz']
factory : ['repriced acme', 'repriced bolt', 'repriced cruz']

What you see: the bad handlers all say cruz; they share one closure cell whose contents are cruz. The three fixes each give acme, bolt, cruz.

Why: each lambda holds a reference to the cell for t, and the cell is updated by every loop iteration.

Java · Spring

Capture must be effectively final.

Loop.javaruns offline
for (String t : tenants) {
  tasks.add(() -> reprice(t));
}
// each t is a new final value

Python

Capture the variable itself.

loop.pyruns offline
for t in tenants:
    tasks.append(lambda: reprice(t))
# one shared t: all see "cruz"

The shift: A Java lambda captures a value that cannot change; a Python closure captures the variable, so a loop that keeps assigning to it changes every closure. See the closure-binding idiom.

Land it I explain that closures capture variables, not values, so all handlers see the loop's last value, and I fix it with partial, a default argument or a factory.

Likely follow-ups
"Why does Java not have this problem?"

Java blocks the situation at compile time. A lambda in Java may use only local variables that are final or effectively final, meaning never reassigned. In a for-each loop the loop variable is a new variable on each iteration, so each lambda captures its own value. If you try to capture a variable that changes, the compiler refuses.

Python has no such rule. A closure captures the variable itself, a cell shared with the enclosing scope, and reads its value when the function is called. That gives you power, since a nested function can update an outer counter with nonlocal. It also gives you the trap: in for t in tenants there is only one t, rebound on every iteration.

The result is the incident in the pricer: all handlers saw the last tenant. When I explain this in an interview, I say that Java forbids it and Python permits it, and that the cure in Python is to bind the value at creation (Q43), because the language will not stop you.

"Does a list comprehension of lambdas have the same problem?"

Yes. A comprehension of lambdas makes one comprehension scope with one loop variable, and every lambda reads that same cell when it finally runs. The demo below shows all three tenants reading 'c'.

q43_late.pyruns offline
lambda: t        -> ['c', 'c', 'c']
lambda t=t: t    -> ['a', 'b', 'c']

The second line shows the default-argument fix, lambda t=t: t, which evaluates t at creation and stores it with each lambda.

The same trap hides in other places where code is created in a loop but runs later. threading.Thread(target=lambda: work(i)) in a loop, loop.call_later and other asyncio callbacks, GUI button handlers, and tasks added to a queue all run after the loop has moved on. Anything deferred is at risk.

My rule is that whenever a function is created in a loop and used later, it must receive its data by argument (partial, a default argument or a factory), and not through the loop variable.

"Why prefer partial to the default-argument trick?"

A lambda with a default is still a function that accepts an extra argument. If a caller passes one positional argument, it silently replaces the bound value.

q43_late.pyruns offline
extra argument   -> oops
partial(upper,t) -> ['A', 'B', 'C']
pickle a lambda  -> PicklingError
pickle a partial -> True

The call hs[0]("oops") returned 'oops', not 'a'. In an event system that passes an event object to every handler, that bug would be very hard to find. A partial stores the bound argument separately and adds call-time arguments after it, so it cannot be overridden by accident, and a wrong call fails loudly.

Partial objects are also introspectable: .func, .args and .keywords show what was bound. And they can be pickled when the function is a module-level one, while a lambda cannot, which matters for multiprocessing, as the last two lines of the demo show.

The default-argument trick is fine for a quick script. In shared code I use partial or a small factory function.

"How would you catch this in review?"

I look for a lambda or an inner def created inside a loop or comprehension that uses the loop variable, where the function is stored, scheduled or returned instead of called straight away. The call at once is safe.

Ruff has this check built in: rule B023, "function definition does not bind loop variable". The same rule exists in the flake8-bugbear plugin. Turning it on in CI catches the bug before a human has to see it.

The second defence is a test. For the pricer, create handlers for three tenants, run each one and assert that it acted on its own tenant. Three different inputs make the failure visible. A test with one tenant would pass even with the bug, because the last value and the only value are the same.

In review I ask "which value does this function see when it finally runs?" If the answer is "whatever the variable holds then", the code needs a fix.

Q44. "What is a decorator, precisely? What does @deco turn into?"

Reveal answer

Strong answer A decorator is a callable that takes a function (or class) and returns a replacement. The syntax @deco above def f(): ... is exactly f = deco(f), executed once, when the def statement runs, which for module-level functions means at import time.

After that, the name f refers to whatever deco returned. Often that is a wrapper function that calls the original with extra behaviour (timing, retries, access checks). Sometimes it is the original function itself, after registering it somewhere (a route table, a plugin list). It can even be something that is not a function at all.

Because a decorator runs at definition time, anything it does outside the wrapper happens at import. The wrapper's body runs on each call. Mixing those two moments up is the most common decorator bug.

Decorators work on classes the same way (@dataclass returns the class, modified). A decorator that takes arguments is one extra layer (Q46).

Picture it A decorator, its import-time effect, and the plain assignment it stands for.

The setup: A traced decorator that prints twice: once when applied, once on each call.

q44_decorator_basics.py · Python 3.14runs offline
def traced(func):
    print(f"[decorate] wrapping {func.__name__}")       # runs at definition time
    def wrapper(*args, **kwargs):
        print(f"[call] {func.__name__}{args}")            # runs on every call
        return func(*args, **kwargs)
    return wrapper

print("defining add ...")
@traced
def add(a, b):
    return a + b
print("add is now:", add)

print("defining sub the long way ...")
def sub(a, b):
    return a - b
sub = traced(sub)                                          # exactly what @traced does

print(add(2, 3), sub(5, 1))

registry = {}
def register(func):                                        # decorator that returns the ORIGINAL
    registry[func.__name__] = func
    return func

@register
def hello():
    return "hi"
print("registry:", registry, "| hello is original:", registry["hello"] is hello)
output · Python 3.14runs offline
defining add ...
[decorate] wrapping add
add is now: <function traced.<locals>.wrapper at 0x7860b2e9f320>
defining sub the long way ...
[decorate] wrapping sub
[call] add(2, 3)
[call] sub(5, 1)
5 4
registry: {'hello': <function hello at 0x7860b2e9f5e0>} | hello is original: True

What you see: both decorate lines print before any call, because they run when the def statement executes. add is now the inner wrapper function, not the original. The register decorator returns the original unchanged, so the name still refers to it.

Why: @traced is a one-line spelling of add = traced(add); nothing about it is special at run time.

Java · Spring

Annotation is metadata.

Svc.javaruns offline
@Transactional
public void save() { ... }
// stored in the class file;
// a framework reads it later

Python

Decorator is code that runs.

svc.pyruns offline
@transactional
def save(): ...
# save = transactional(save)
# runs now, replaces the function

The shift: A Java annotation does nothing until a framework acts on it; a Python decorator acts at once and can replace what you defined. See the wraps idiom.

Land it I say @deco is f = deco(f) run once at definition time, usually returning a wrapper, and I keep one-time work outside the wrapper and per-call work inside it.

Likely follow-ups
"Does the decorator run for every call?"

No. The decorator function runs once per decorated function, when the def statement is executed. Only the wrapper it returns runs on each call. The demo shows both moments.

q44_when.pyruns offline
before def
decorating price
after def
calling price
calling price

"decorating price" appears once, between the two print lines of the module, and "calling price" appears on each call. For a module-level function, the first moment is import time.

That has two consequences. Slow work in the decorator body, such as opening a connection or reading a file, slows every import of the module and runs in tests that only import it. And a classic bug is writing start = time.time() in the decorator body instead of inside the wrapper, so you measure import time forever and report the same number on every call.

My rule: one-time set-up goes in the decorator body, per-call work goes in the wrapper, and neither does I/O at import.

"Can I decorate a class or a method?"

Yes to both. A class decorator receives the class and returns a class, usually the same one, modified. @dataclass and @functools.total_ordering work this way.

A method is decorated while the class body runs, before the function becomes a bound method. So the wrapper is a plain function, and its first argument at call time is self. A decorator that is written with def wrapper(*args, **kwargs) passes self along without any special handling.

@staticmethod, @classmethod and @property are decorators too, and they return descriptor objects (Q32). That is why their order against your own decorator matters. Put @property on the outside, because it needs a function to turn into a descriptor. If a descriptor decorator sits below yours, your wrapper receives the descriptor object and not a function, and calling it may fail.

When I write a decorator for methods and plain functions alike, I test both. A decorator that uses a global or caches by arguments also has to decide whether self is part of the key.

"What does the traceback look like through a decorator?"

A traceback shows one extra frame for each wrapper between the caller and the original function. With stacked decorators you see several wrapper lines in a row, then the original. It looks noisy but it is normal, and it tells you the exact path of the call.

functools.wraps does not hide these frames. It copies the name, docstring, module and annotations, and sets __wrapped__, so tools show the right name, but the wrapper still runs and still appears in the stack.

The same thing shows in profilers. Time spent in the wrapper's own code is attributed to the wrapper's file and line, usually inside the decorator module, and the original function appears below it. So when a decorated function looks slow in a profile, subtract the original's time and look at what the wrapper does around it: logging, locking, retries or argument checks.

For readable tracebacks I keep wrappers small and give them clear names in the decorator module. If a decorator adds several layers, I look at whether it can be one layer.

"Is a decorator the same as the decorator design pattern?"

They are related but different, and an interviewer likes to hear that. The decorator design pattern (from the Gang of Four book) wraps an object in another object with the same interface, to add behaviour at run time. A BufferedReader around a file is an example. A Python decorator is a language feature: syntax that replaces a function or class at definition time with the result of calling another function.

Python decorators are often used to implement the pattern for functions, because a wrapper function has the same call interface as the original. But they can do things the pattern does not, such as registering a function in a table and returning it unchanged, which is not wrapping.

The reverse is also true. You can apply the design pattern in Python without any @ syntax, by writing a class that holds another object and forwards its methods.

So I say: "the @ syntax is a tool, and the pattern is an idea; one can implement the other". It shows that you separate syntax from design.

Q45 · Scenario. "After decorating, func.__name__ is "wrapper" and your routing and logging break. Fix it."

Reveal answer

Strong answer The decorator replaced func with the inner wrapper, so the name, docstring, module, annotations and signature are now the wrapper's. Anything that reads them (a router that registers by function name, a logger that prints the name, help(), a test collector) sees wrapper. Several routes registered under the same name wrapper overwrite each other.

The fix is functools.wraps: put @functools.wraps(func) on the wrapper. It copies __name__, __qualname__, __doc__, __module__, __annotations__ and updates __dict__, and it sets __wrapped__ to the original function. inspect.signature follows __wrapped__, so tools see the real parameters.

Make it a rule: every decorator that returns a wrapper uses wraps, no exceptions. A decorator without it is a bug waiting for the first framework that inspects names. See the wraps idiom.

Remember, wraps copies metadata only; it does not make a wrapper's behaviour correct for async functions, generators or methods. An async def needs an async def wrapper.

Picture it The name lost and restored, and a route table colliding.

The setup: A decorator without and with wraps, and a route table keyed by function name.

q45_wraps.py · Python 3.14runs offline
import functools, inspect

def bad(func):
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)
    return wrapper

def good(func):
    @functools.wraps(func)                       # ✅ copies metadata, sets __wrapped__
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)
    return wrapper

@bad
def price_order(order_id: int, rush: bool = False):
    """Price one order."""

@good
def price_cart(cart_id: int, rush: bool = False):
    """Price one cart."""

for f in (price_order, price_cart):
    print(f"{f.__name__:12} doc={f.__doc__!r:16} signature={inspect.signature(f)}")
print("original reachable:", price_cart.__wrapped__.__name__)

routes = {}
for f in (price_order, bad(lambda: None)):       # two different functions, both named 'wrapper'
    routes[f.__name__] = f
print("routes registered:", list(routes), "<- one route lost")
output · Python 3.14runs offline
wrapper      doc=None             signature=(*args, **kwargs)
price_cart   doc='Price one cart.' signature=(cart_id: int, rush: bool = False)
original reachable: price_cart
routes registered: ['wrapper'] <- one route lost

What you see: the bad wrapper reports wrapper, loses the docstring, and shows (*args, **kwargs) as its signature. The good one keeps price_cart, its docstring and its real signature, and exposes the original through __wrapped__. The route table ends up with one entry.

Why: the name used as a key was the same for every undecorated wrapper, so later registrations replaced earlier ones.

Wrapper leaks

Everything is called "wrapper".

bad.pyruns offline
def deco(func):
    def wrapper(*a, **k):
        return func(*a, **k)
    return wrapper

With wraps

Metadata survives.

good.pyruns offline
def deco(func):
    @wraps(func)
    def wrapper(*a, **k):
        return func(*a, **k)
    return wrapper

The shift: One line, @wraps(func), makes the wrapper look like the function it replaces.

Land it I put @functools.wraps(func) on every wrapper so the name, docstring, signature and __wrapped__ survive, and I test that a decorated function keeps its __name__.

Likely follow-ups
"What does __wrapped__ give me?"

functools.wraps sets wrapper.__wrapped__ = func, a direct link to the function that was decorated. inspect.signature follows it, so tools show the original parameters. A test can call price.__wrapped__(3) to run the undecorated logic without the extra behaviour.

q45_unwrap.pyruns offline
price.__name__          -> price
inspect.signature(price) -> (x: int, y: int = 2)
unwrap(price).__name__  -> price
price.__wrapped__.__wrapped__(3) -> 6
chain broken at plain: g.__wrapped__.__name__ -> w
unwrap(g).__name__ -> w

Two stacked decorators with wraps make a chain. inspect.unwrap(f) follows it to the end, and manual f.__wrapped__.__wrapped__ does the same one step at a time.

The last two lines show what happens when one decorator, plain, does not use wraps. The chain is broken at that layer, and both lookups stop at the wrapper named w. One careless decorator is enough to hide everything below it from tools. That is why I make wraps a rule for every decorator.

"Does wraps fix type checkers?"

No. wraps fixes run-time metadata and nothing else. A type checker does not run your code, so it never sees the effect of wraps. For static typing, the wrapper's signature must be written with ParamSpec and TypeVar so the checker knows that the decorated function keeps its parameters and return type (Q48, Q121).

Without that, a tool such as mypy infers the type of the decorated function as Callable[..., Any]. Every call is then accepted, even with the wrong arguments, and the return value is Any, so mistakes slip past the checker. You lose most of the value of your annotations on exactly the functions that are decorated, which are often the important ones: handlers, retries and cached calls.

A good decorator therefore has both. @functools.wraps(func) serves the run-time tools, such as loggers, routers and help(). Annotations with Callable[P, R] and ParamSpec serve the type checkers. Neither can replace the other.

"What breaks with async def functions?"

A plain wrapper around an async def function calls it and gets back a coroutine object, without running anything yet. The wrapper returns that coroutine at once. Anything the wrapper does around the call, such as timing, retrying or catching errors, therefore sees only the creation of the coroutine.

q45_async.pyruns offline
sync wrapper measured 0.002 ms
async wrapper measured 100 ms

The function sleeps for 0.1 s, and the synchronous timer reports a few microseconds. A try/except in a sync wrapper would also miss every exception, because errors appear when the coroutine is awaited later. A retry decorator would "succeed" on the first try and never retry anything.

The fix is an async def wrapper that awaits the call. To support both kinds with one decorator, check inspect.iscoroutinefunction(func) at decoration time and return the matching wrapper. wraps works for both, but it does not make a sync wrapper async-aware.

"How do I write a test for this?"

Write one test in the decorator's own test file. It asserts that a decorated function keeps its identity: decorated.__name__ == "original_name", decorated.__doc__ is the original's, and inspect.signature(decorated) == inspect.signature(original).

  1. Identity: name, docstring and module are those of the original function, not wrapper.
  2. Signature: the parameters seen by inspect.signature match, including defaults and annotations.
  3. Unwrapping: inspect.unwrap(decorated) is the original function object.

The test belongs with the decorator, once, and not with every decorated function. If twenty functions use the decorator, one test covers all of them.

A cheap project-wide guard is a code review rule or a lint check: any inner function returned from a decorator must carry @wraps. A short script can search for a def wrapper not preceded by @wraps, or a decorator test can loop over all your decorators in one parametrised test. Cheap checks like this keep the rule true as the team grows.

Q46. "Write a decorator that takes arguments, such as @retry(times=3)."

Reveal answer

Strong answer @retry(times=3) first calls retry(times=3), and the result of that call is the decorator that is applied to the function. So a decorator with arguments is a function that returns a decorator that returns a wrapper: three layers.

  1. Outer: retry(times) receives the configuration and returns the decorator. It runs once, at definition time.
  2. Middle: decorator(func) receives the function and returns the wrapper. It also runs once, right after.
  3. Inner: wrapper(*args, **kwargs) runs on every call, using times and func from the enclosing scopes (they are closure variables, Q43).

@retry(times=3) def f() is f = retry(times=3)(f). Put @functools.wraps(func) on the inner wrapper (Q45). Validate the arguments in the outer layer so a bad value fails at import, not on the first failure in production.

A frequent mistake is writing @retry without parentheses on a factory: Python then passes the function as times. Here the mistake fails already at decoration time with a confusing message. Either require the parentheses or support both forms by checking whether the first argument is callable.

Picture it A retry decorator, a flaky function, and the number of attempts it needed.

The setup: A function that fails twice and succeeds on the third call, decorated with times=3, and one that always fails.

q46_decorator_factory.py · Python 3.14runs offline
import functools

def retry(times=3):
    if times < 1:
        raise ValueError("times must be >= 1")           # fails at import, not in production
    def decorator(func):                                  # layer 2: receives the function
        @functools.wraps(func)
        def wrapper(*args, **kwargs):                     # layer 3: runs on each call
            last = None
            for attempt in range(1, times + 1):
                try:
                    return func(*args, **kwargs)
                except Exception as exc:
                    last = exc
                    print(f"  attempt {attempt}/{times} failed: {exc}")
            raise last
        return wrapper
    return decorator                                      # layer 1 returns layer 2

calls = {"n": 0}

@retry(times=3)
def flaky():
    calls["n"] += 1
    if calls["n"] < 3:
        raise ConnectionError(f"timeout #{calls['n']}")
    return "ok"

print("flaky ->", flaky())

@retry(times=2)
def always_down():
    raise ConnectionError("down")

try:
    always_down()
except ConnectionError as e:
    print("always_down gave up with:", e)

try:
    @retry                                                # ❌ TRAP: forgot the parentheses
    def oops():
        pass
    oops()
except TypeError as e:
    print("@retry without () ->", e)
output · Python 3.14runs offline
  attempt 1/3 failed: timeout #1
  attempt 2/3 failed: timeout #2
flaky -> ok
  attempt 1/2 failed: down
  attempt 2/2 failed: down
always_down gave up with: down
@retry without () -> '<' not supported between instances of 'function' and 'int'

What you see: flaky fails twice, then succeeds on attempt 3; always_down re-raises the last error after two attempts; and the missing parentheses version breaks at once, with a confusing comparison error, because the function was passed in as times.

Why: retry(times=3) is evaluated first and returns the real decorator; @retry alone passes oops as the only argument.

Java · Spring

Annotation with attributes.

Svc.javaruns offline
@Retryable(maxAttempts = 3)
public String call() { ... }
// framework proxies the bean

Python

A factory returns the decorator.

svc.pyruns offline
@retry(times=3)
def call(): ...
# call = retry(times=3)(call)

The shift: Spring configures behaviour by reading attributes later; Python runs retry(times=3) now to build the decorator. See the decorator-factory idiom.

Land it I write three layers, a factory for the arguments, a decorator for the function and a wrapper for the call, with wraps, validated arguments, and parentheses always required.

Likely follow-ups
"How can @retry and @retry(times=3) both work?"

Make the function a parameter that defaults to None, and make the options keyword-only. When func is given, you were used bare (@retry), so decorate it directly. When it is None, you were called with options (@retry(times=5)), so return a decorator that waits for the function.

retry_both.pyruns offline
def retry(func=None, *, times=3):
    if func is None:
        return lambda f: retry(f, times=times)
    @functools.wraps(func)
    def wrapper(*a, **k):
        return func(*a, **k)
    return wrapper

The star before times matters. It stops @retry(3) from putting 3 into the func slot and turning the call into nonsense, so a mistake fails clearly.

I tested both forms, and they print times = 3 and times = 5. Is it worth it? It saves callers the empty brackets, but it makes the decorator harder to read. In shared code I require the brackets: one form, one habit, no magic. I support both only for a public library decorator where users expect it.

"Where do the arguments live between calls?"

In the closure of the wrapper. When retry(times=4) returns the decorator, and the decorator returns the wrapper, the wrapper keeps references to the variables it uses from the outer functions. Those are cell variables, and the wrapper function object carries them in __closure__. Each decorated function gets its own cells, so two functions decorated with different times do not interfere.

q46_closure.pyruns offline
('func', 'times')
[<function flaky at 0x79d98667ade0>, 4]
flaky

The first line lists the free variables, the second their values (the original function and the number 4), and the third is __wrapped__. This is how you check what configuration a decorated function carries, without reading its source.

Closure cells live as long as the wrapper. If a decorator argument is a big object, such as a cache or a client, it stays in memory as long as the decorated function exists, which is usually the life of the program. Closures can also be updated with nonlocal inside the wrapper, which is one way to keep a call counter without a class.

"Should I use a class instead?"

Yes, it is a valid alternative. A class with __init__(self, times) stores the options, and __call__(self, func) returns the wrapper (or the decorated object). @Retry(times=3) then works like the function form.

The class version is clearer when the decorator has state you want to inspect afterwards: a counter of retries, a statistics object, or a registry. It can have several methods, such as reset() or stats(), and isinstance(f, Retry) can recognise a decorated function if the class itself wraps the function and defines __call__. If you do that, remember to copy the metadata with functools.update_wrapper(self, func).

The function version is shorter and has a tested shape that every Python developer knows. It is fine for most cases, and I start there.

I switch to a class when I find myself attaching attributes to the wrapper function by hand, when I need isinstance checks, or when the decorator has several methods or shared state. A class also reads better when the options are many.

"How do I test it quickly?"

Take away the real clock and the real failure. A retry decorator depends on time (sleep) and randomness (jitter). If both are parameters, a test passes in a fake sleep that records its arguments and returns at once, and a fake random source, so the test runs in milliseconds and the same way every time.

  1. Fake the function: a function that raises ConnectionError a known number of times, then returns a value.
  2. Count the calls: with times=3 and a function that fails twice, assert it was called exactly 3 times and the result is the final value.
  3. Check the delays: the fake sleep was called with the expected, capped values.
  4. Check the failure path: a function that always fails raises the last exception after times attempts, and a TypeError (not retryable) is raised on the first call.

Q48 shows a version with injectable sleep and rng arguments, written for exactly this. A test that really sleeps for two seconds will be skipped by tired developers sooner or later.

Q47. "In what order are stacked decorators applied, and in what order do they run?"

Reveal answer

Strong answer Decorators are applied bottom to top, like function composition written upward: @a @b def f means f = a(b(f)). The one nearest the def wraps the original first.

They run top to bottom on the way in, and bottom to top on the way out. Calling f() enters a's wrapper first, which calls b's wrapper, which calls the original. The original returns, then b's code after the call finishes, then a's. The outermost decorator, the top one, sees the call first and the result last.

So the order matters. A caching decorator above an authorisation check serves cached results to people who should be refused; below it, the check runs on every call. A retry above a timeout retries the whole timed call; a timeout above a retry limits the total time.

Rule of thumb: put the decorator that should see every call (logging, authorisation, metrics) on top, and the one closest to the real work (caching, retry) below. And stacking @staticmethod, @classmethod or @property with your own: those must usually be outermost, because they expect a plain function.

Picture it Two decorators that print on application and on each call.

The setup: @outer above @inner, applied to one function, called once.

q47_stacked_decorators.py · Python 3.14runs offline
import functools

def tag(name):
    def decorator(func):
        print(f"apply  {name}")                           # runs while decorating
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            print(f"  enter {name}")
            result = func(*args, **kwargs)
            print(f"  exit  {name}")
            return result
        return wrapper
    return decorator

print("--- decorating")
@tag("outer")
@tag("inner")
def work():
    print("    work body")
    return "done"

print("--- calling")
print("result:", work())

print("--- manual equivalent")
def work2():
    print("    work body")
    return "done"
work2 = tag("outer")(tag("inner")(work2))
print("result:", work2())
output · Python 3.14runs offline
--- decorating
apply  inner
apply  outer
--- calling
  enter outer
  enter inner
    work body
  exit  inner
  exit  outer
result: done
--- manual equivalent
apply  inner
apply  outer
  enter outer
  enter inner
    work body
  exit  inner
  exit  outer
result: done

What you see: inner is applied first and outer second. On the call, outer enters first and exits last, with inner in the middle, and the manual composition prints exactly the same.

Why: @outer @inner def f is f = outer(inner(f)), so outer's wrapper holds inner's wrapper, which holds the original.

Java · Spring

Order set by @Order or config.

Aspects.javaruns offline
@Order(1) class Auth { ... }
@Order(2) class Cache { ... }
// priority lives in numbers,
// far from the method

Python

Order is the line order.

stack.pyruns offline
@auth        # runs first
@cache       # runs second
def get(): ...
# get = auth(cache(get))

The shift: With Python stacking the order is visible at the definition, read top to bottom as the order of entry.

Land it I say decorators are applied bottom-up and run top-down, f = a(b(f)), and I place authorisation and logging on top of caching and retry for a reason I can state.

Likely follow-ups
"Give a real case where order matters."

The standard case is a cache and a security check. Order decides whether the check runs.

q47_order.pyruns offline
cache above check, anonymous caller : 2
check above cache, anonymous caller : denied

With @cache above @login_required, the first user's result is stored. A later anonymous caller hits the cache, and the check is never reached. With the check above the cache, every call is checked before the cache can answer. The security check must be on the outside.

The mirror case is time. @retry above @timeout(2) gives each attempt two seconds, so three attempts can take six. @timeout(2) above @retry caps the whole thing at two seconds including all retries. Both are valid; they mean different things, and the order is the way you say which one you want.

I draw the call path on paper: the top decorator is the outermost layer, and the call enters it first.

"What about @property and @lru_cache?"

@property must be the outermost, because it needs a function to turn into a descriptor. Putting @lru_cache on the outside fails, since a property object is not a function.

q47_prop.pyruns offline
1
TypeError: Expected first argument to be an integer, a callable, or None

The working order, @property above @lru_cache, runs but has the leak from Q50: the cache key includes self, so every instance stays in the cache and is never freed. It also gives each lookup a hash of self, which uses __hash__, and fails if the class defines __eq__ without __hash__ (Q22).

For a value that is computed once per instance, use functools.cached_property. The value lives in the instance's own __dict__, dies with it, and needs no hash. If the computation depends only on inputs and not on the object, move it to a module-level function and cache that.

"How do I see the whole stack on a function?"

Follow the chain of __wrapped__ links. inspect.unwrap(f) goes down to the original function, and you can do it by hand with f.__wrapped__, then f.__wrapped__.__wrapped__. Each decorator that used functools.wraps adds one link, so the number of links equals the number of well-behaved layers.

To see the layers themselves, you can print each function on the way: while hasattr(f, "__wrapped__"): print(f); f = f.__wrapped__. Each printed line is a wrapper with the same name as the original, but a different address and often a different source file, so the file name tells you which decorator it came from. The wrapper's __code__.co_filename and __qualname__ show where it was defined.

If one decorator forgot wraps, the chain breaks at that layer, and everything under it is hidden from this method. That is another reason to require wraps everywhere (Q45).

When I debug a surprising call, I print the chain first, because it often shows a layer nobody remembered adding, like a cache or a retry from a shared library.

"Does the order differ for class decorators?"

Class decorators also apply bottom-up, and the order can matter in ways that are easy to miss. The classic case is decorators that make a new class. @dataclass(slots=True) builds a new class object and returns it, and the original is thrown away.

q47_class.pyruns offline
register above dataclass keeps final class : True
register below dataclass keeps final class : False

register above the dataclass sees the final class. register below it sees the original, which is discarded, so the registry holds a class nobody else has. The same thing happens with any other decorator that replaces the class, and it fails only when something compares or instantiates the registered class.

Decorators that read what already exists need the order right too. total_ordering checks for the comparison methods that are defined at that moment, so the class must have them before it runs. When decorators interact, I test the combination, not each in isolation.

Q48 · Design. "Write a retry decorator with exponential backoff, jitter and a list of retryable exceptions, typed with ParamSpec."

Reveal answer

Strong answer Design points before code. What to retry: only exceptions you name (ConnectionError, TimeoutError), never bare Exception, never KeyboardInterrupt; a programming error such as TypeError must fail at once. How long to wait: exponential backoff, base * 2 ** attempt, capped at a maximum, so ten attempts do not become ten minutes.

Jitter: a random factor ("full jitter": a random value between 0 and the capped delay) so a hundred clients that failed together do not retry together and hit the server in a synchronised wave. When to stop: a maximum number of attempts, and optionally a deadline. Typing: ParamSpec so the decorated function keeps its parameter types, and TypeVar for the return type.

Make time and randomness injectable (sleep= and rng=), so tests run instantly and deterministically. Log each retry with the attempt number and the delay. Re-raise the last exception, keeping the chain (raise ... from), after the final attempt.

Only retry operations that are idempotent, meaning safe to repeat. Retrying "charge the card" without an idempotency key charges twice.

Picture it The typed decorator, a flaky call retried with a recorded fake clock, and a non-retryable error.

The setup: A fake sleep records the delays; a seeded random generator makes the jitter repeatable.

q48_retry_backoff.py · Python 3.14runs offline
import functools, random
from typing import Callable, ParamSpec, TypeVar

P = ParamSpec("P")
R = TypeVar("R")

def retry(*, times: int = 4, base: float = 0.1, cap: float = 2.0,
          retry_on: tuple[type[BaseException], ...] = (ConnectionError, TimeoutError),
          sleep: Callable[[float], None] = None, rng: Callable[[], float] = random.random,
          ) -> Callable[[Callable[P, R]], Callable[P, R]]:
    if sleep is None:
        import time
        sleep = time.sleep
    def decorator(func: Callable[P, R]) -> Callable[P, R]:
        @functools.wraps(func)
        def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
            for attempt in range(times):
                try:
                    return func(*args, **kwargs)
                except retry_on as exc:
                    if attempt == times - 1:
                        raise                                   # out of attempts: re-raise the last one
                    delay = rng() * min(cap, base * 2 ** attempt)   # full jitter
                    print(f"  attempt {attempt + 1} failed ({exc}); sleeping {delay:.3f}s")
                    sleep(delay)
        return wrapper
    return decorator

slept = []
rnd = random.Random(7)

state = {"calls": 0}
@retry(times=4, sleep=slept.append, rng=rnd.random)
def fetch_rate(currency: str) -> float:
    state["calls"] += 1
    if state["calls"] < 3:
        raise ConnectionError("upstream reset")
    return 1.08

print("result:", fetch_rate("EUR"), "| calls:", state["calls"], "| delays:", [round(s, 3) for s in slept])

@retry(times=4, sleep=slept.append)
def broken() -> None:
    raise TypeError("bug, not a network problem")

try:
    broken()
except TypeError as e:
    print("TypeError was NOT retried:", e, "| total sleeps so far:", len(slept))

@retry(times=3, sleep=slept.append, rng=lambda: 1.0)           # worst-case jitter shows the cap
def down() -> None:
    raise TimeoutError("down")
try:
    down()
except TimeoutError:
    print("gave up; last delays with jitter=1.0:", [round(s, 2) for s in slept[-2:]])
output · Python 3.14runs offline
  attempt 1 failed (upstream reset); sleeping 0.032s
  attempt 2 failed (upstream reset); sleeping 0.030s
result: 1.08 | calls: 3 | delays: [0.032, 0.03]
TypeError was NOT retried: bug, not a network problem | total sleeps so far: 2
  attempt 1 failed (down); sleeping 0.100s
  attempt 2 failed (down); sleeping 0.200s
gave up; last delays with jitter=1.0: [0.1, 0.2]

What you see: two failures, two recorded sleeps, then success on the third call; the TypeError propagated at once with no sleep; with jitter pinned at 1.0 the delays show the plain exponential schedule (0.1 s, then 0.2 s).

Why: injecting sleep and rng turns a slow, random behaviour into a test that finishes in microseconds and gives the same answer every time.

Fixed delay

Everyone retries at once.

fixed.pyruns offline
for _ in range(3):
    try: return call()
    except Exception: sleep(1)

Backoff plus jitter

Spread out, capped.

smart.pyruns offline
delay = rng() * min(cap,
                    base * 2**n)
sleep(delay)

The shift: A fixed one-second retry synchronises a crowd of clients; random, growing delays spread the load and give the server time to recover. See the decorator-factory idiom.

Land it I retry only named, idempotent-safe exceptions with capped exponential backoff and full jitter, inject sleep and rng for tests, type it with ParamSpec, and re-raise the last error.

Likely follow-ups
"Why full jitter and not a small random addition?"

Because spreading the retries over the whole interval is the best way to flatten the load. If every client waits "the backoff plus a little random", they still arrive in a tight bunch around the same moment. With full jitter, each client picks a random time anywhere between zero and the cap for that attempt, so retries are spread out.

q48_backoff.pyruns offline
attempt 0: wait a random time in [0, 0.5] s
attempt 1: wait a random time in [0, 1.0] s
attempt 2: wait a random time in [0, 2.0] s
attempt 3: wait a random time in [0, 4.0] s
attempt 4: wait a random time in [0, 8.0] s
attempt 5: wait a random time in [0, 8.0] s
worst-case total wait: 23.5 s

With base 0.5 s and a cap of 8 s, the upper bound doubles until it hits the cap, and the worst-case total wait is 23.5 s. The actual wait is random and on average about half of it.

An often-cited post on the AWS Architecture Blog compared no jitter, equal jitter, full jitter and decorrelated jitter, and found that jitter cuts the total number of calls and the completion time sharply. I would check that article before quoting numbers.

The cost is that one client may wait very little on one attempt. That is fine. The average delay still grows exponentially, and the server sees a smooth load instead of waves.

"What does ParamSpec change for callers?"

It lets the type checker keep the exact parameters of the decorated function. ParamSpec (named P) captures "whatever parameters the function has", and Callable[P, R] says the wrapper takes the same ones and returns the same type R. A checker such as mypy or pyright then rejects fetch_rate(5) if the original is def fetch_rate(currency: str) -> float, and reveal_type(fetch_rate) shows (currency: str) -> float.

Without it, the decorated function is typed as Callable[..., Any]. Every call is accepted, whatever the arguments, and the result is Any, so the checker stops helping on the functions that matter most.

Two rules: P.args and P.kwargs must be used together, as *args: P.args, **kwargs: P.kwargs, and the wrapper is annotated to return R. Concatenate (Q121) adds or removes a leading parameter. And ParamSpec changes nothing at run time, so wraps is still needed.

"What about async functions?"

You need a separate version. A synchronous wrapper around an async def function would return the coroutine at once, unawaited, so nothing is retried: the failure happens later, in the caller, outside your try block (Q45).

The async version is async def wrapper(...), with result = await func(*args, **kwargs) inside the retry loop, and await asyncio.sleep(delay) between attempts. A blocking time.sleep in async code would freeze the whole event loop, which is a worse bug than not retrying.

To support both with one name, check inspect.iscoroutinefunction(func) once, when decorating, and return the matching wrapper. The two bodies are almost the same, so I keep the shared logic in a helper that computes delays.

In production code I use a library such as tenacity or backoff. They handle sync and async, stop conditions, callbacks and logging, and have been tested by many users. In an interview I write my own, to show I understand what they do.

"When should I not retry at all?"

Do not retry when the operation is not idempotent and has no idempotency key. Charging a card twice is the standard example. Do not retry permanent errors such as HTTP 400, 401 or 404 or a validation failure, because the next attempt fails the same way and wastes time. Do not retry when the caller already has a deadline that the retries would break. And do not retry when a circuit breaker should open instead, because more calls make an overloaded dependency worse.

Retries multiply load during an outage. Suppose 1,000 requests per second each retry 3 times. A failing dependency then sees up to 4,000 calls per second, at the moment it is weakest. A retry budget protects it: for example, allow retries only up to 10 % of the normal request rate, which here is 100 extra calls per second, and fail fast beyond that.

Ask three questions. Is it safe to repeat? Could the error go away by itself? Will the caller still want the answer?

Q49. "Java annotations versus Python decorators — what is the fundamental difference?"

Reveal answer

The real test Whether you say "annotations are inert metadata read later by something else; decorators are executed code that can replace the function".

Strong answer A Java annotation is declarative metadata. Writing @Transactional stores a note in the class file. By itself it does nothing; a framework (Spring, via reflection and generated proxies) reads the note later and decides what to do. The annotated method is not changed by the annotation.

A Python decorator is executable code. @deco runs deco(f) at the moment the function is defined and binds the name to the result. So a decorator can wrap the function, replace it, register it, or leave it alone and only attach data.

Consequences. In Python, behaviour is visible and traceable in ordinary code: step into deco and see everything. In Java you need to know what the framework does with the note. Python decorators run at import time, so they can slow start-up or fail on import; Java annotation processing happens at compile time or at framework start-up.

Python can also write the metadata-only style: a decorator that just sets func.route = "/x" and returns the function, which a framework scans later, which is exactly how Flask-style and pytest marks work.

The Python counterpart of "annotation" in the metadata sense is a decorator that only tags; in the behaviour sense it is a wrapper.

Picture it A tag-only decorator that a scanner reads later, and a wrapping decorator that changes behaviour now.

The setup: @route stores a path on the function and returns it unchanged; @timed replaces the function with a wrapper.

q49_metadata_vs_wrapper.py · Python 3.14runs offline
import functools

def route(path):                                     # metadata only: like a Java annotation
    def tag(func):
        func.route = path
        return func                                  # the same function object comes back
    return tag

def timed(func):                                     # behaviour: replaces the function
    @functools.wraps(func)
    def wrapper(*a, **k):
        print("  [timed] before call")
        return func(*a, **k)
    return wrapper

class Api:
    @route("/orders")
    def orders(self):
        return "orders"

    @timed
    def prices(self):
        return "prices"

print("orders.route =", Api.orders.route, "| still the original function:", Api.orders.__qualname__)
print("prices has route?", hasattr(Api.prices, "route"), "| prices is wrapper?", Api.prices.__wrapped__ is not Api.prices)

table = {f.route: name for name, f in vars(Api).items() if hasattr(f, "route")}    # the 'framework' scan
print("scanned routes:", table)
print(Api().prices())
output · Python 3.14runs offline
orders.route = /orders | still the original function: Api.orders
prices has route? False | prices is wrapper? True
scanned routes: {'/orders': 'orders'}
  [timed] before call
prices

What you see: orders still is the original function with a route attribute, found later by a scan that stands in for the framework. prices is a wrapper that prints before calling the original.

Why: both are decorators; the first only attaches data, the second changes what gets called.

Java · Spring

Metadata, read by reflection.

Ctl.javaruns offline
@GetMapping("/orders")
List<Order> orders() { ... }
// stored in class file;
// Spring scans and wires it

Python

Code that runs and may replace.

ctl.pyruns offline
@app.get("/orders")
def orders(): ...
# runs now: registers orders,
# returns the function

The shift: Annotation = a note someone else may read later; decorator = a function call that happens right now. See the wraps idiom.

Land it I say an annotation is inert metadata a framework reads, a decorator is a function call at definition time that can wrap, register or tag, and Python's @app.get is a decorator that registers.

Likely follow-ups
"Does Python have something closer to Java annotations?"

Yes, in three forms. First, type annotations. x: int stores metadata in __annotations__. The interpreter ignores it, but tools read it: type checkers, Pydantic, FastAPI and dataclasses. That is close to Java annotations in spirit: inert notes that a framework interprets.

Second, typing.Annotated[int, Field(gt=0)] attaches arbitrary metadata to a type. Pydantic and FastAPI read it to build validation and documentation. This is the closest match to a Java annotation with attributes, such as @Min(1) on a field.

Third, a decorator that only tags. def route(path): def deco(f): f.route = path; return f; return deco sets an attribute and returns the same function. A framework scans for route later, and this is how pytest marks and many web routers work.

So Python has both ideas: declarative metadata through annotations, and executable decoration. In an interview I name the difference between "a note a framework reads" and "code that runs at definition time".

"What is the cost of running at import time?"

Every decorated function costs one extra call when the module is imported. A few hundred route registrations cost almost nothing. The problem begins when a decorator body does something heavy or fragile at import: opening a database connection, reading a config file, calling a network service, or starting a thread.

Those actions run in every process that imports the module: a unit test that wanted one helper, a command-line tool that wanted only --help, every worker process. Start-up gets slower, failures appear at import with confusing tracebacks, and tests need the real dependency just to load the file.

My rules are short. The decorator body may build wrappers, set attributes and update a registry (a dictionary, a list). It does not do I/O. Work that needs a resource waits for the first call, or for an explicit start-up function, such as an init() or an application factory.

"How does Spring do it without decorators?"

It uses proxies built from annotations. At start-up, Spring scans the beans for annotations such as @Transactional. For each one, it wraps the bean in a proxy, either a JDK dynamic proxy for interfaces or a generated subclass (CGLIB). When your code calls the method, the proxy runs the extra logic (begin a transaction, call the real method, commit or roll back) around it.

The annotated method is untouched. The annotation is only a marker, and the behaviour lives in the proxy.

A Python decorator does the same job with less machinery. There is no container and no scanning, since the decorator itself builds the wrapper and replaces the function at the line where it is written. You can read the code to see exactly what runs.

One consequence: Spring has the well-known self-invocation trap, where a call from inside the same class skips the proxy. A Python wrapper has no such gap.

"What are the downsides of decorators?"

There are four main downsides.

  1. Hidden control flow: a retry, a cache, a transaction or a permission check is invisible at the call site. Someone reading price(cart) cannot see it.
  2. Order surprises: stacked decorators apply bottom-up and interact (Q47).
  3. Broken introspection: without wraps, names, docstrings and signatures are lost (Q45).
  4. Typing cost: without ParamSpec, the decorated function becomes Callable[..., Any] for the type checker (Q48).

There is also a testing cost: you have to decide whether tests call the wrapper or __wrapped__, and decorators that read global state are hard to isolate.

My rule is to use a decorator for cross-cutting behaviour that is the same in many places, such as logging, timing, retries, caching and access checks. If the behaviour is specific to one function, I write it as ordinary code in the body, where everyone can see it.

Q50 · Scenario. "@lru_cache on a method leaks memory. Why, and what do you do instead?"

Reveal answer

Strong answer functools.lru_cache stores results in a cache keyed by the call arguments. On a method, the first argument is self, so the cache holds a strong reference to every instance it was ever called with, as part of the keys. The instance cannot be freed while its entry sits in the cache, and with maxsize=None the cache never evicts, so instances accumulate until the process restarts.

In a service that creates one object per request, that is a slow leak that matches the "memory grows over a day" symptom (Q12).

Fixes, in order of preference. Cache a pure function keyed by values, not by self: move the computation to a module-level function or a @staticmethod that takes only the inputs, and call it from the method. functools.cached_property when the value is computed once per instance from its own state: the value lives in the instance's __dict__ and dies with it.

A per-instance cache created in __init__ (self._cached = lru_cache(maxsize=128)(self._compute)), which creates a reference cycle (instance, cache, bound method) that the cycle collector frees. A bounded maxsize if you must keep the decorator on the method, to cap the damage.

Python 3.9 added functools.cache (an unbounded lru_cache), which has the same trap and a more tempting name.

Picture it An instance that cannot die, and three fixes that let it go.

The setup: A Pricer class with a cached method; create an instance, delete it, and ask a weak reference whether it is still alive.

q50_lru_cache_method.py · Python 3.14runs offline
import functools, gc, weakref

class Bad:
    def __init__(self, rate):
        self.rate = rate
    @functools.lru_cache(maxsize=None)                  # ❌ TRAP: self becomes part of the key
    def price(self, qty):
        return qty * self.rate

class CachedProp:
    def __init__(self, rate):
        self.rate = rate
    @functools.cached_property                          # ✅ value lives in the instance
    def base(self):
        return self.rate * 100

@functools.lru_cache(maxsize=128)                       # ✅ keyed by values, not by self
def price_for(rate, qty):
    return qty * rate

class ByValue:
    def __init__(self, rate):
        self.rate = rate
    def price(self, qty):
        return price_for(self.rate, qty)

def survives(factory):
    obj = factory()
    ref = weakref.ref(obj)
    del obj
    gc.collect()
    return ref() is not None

b = Bad(2)
b.price(3)
print("Bad cache_info:", Bad.price.cache_info())
print("Bad instance survives del + gc.collect():", survives(lambda: (lambda o: (o.price(3), o)[1])(Bad(2))))
print("cached_property instance survives:", survives(lambda: (lambda o: (o.base, o)[1])(CachedProp(2))))
print("by-value instance survives       :", survives(lambda: (lambda o: (o.price(3), o)[1])(ByValue(2))))
print("by-value cache_info:", price_for.cache_info())
output · Python 3.14runs offline
Bad cache_info: CacheInfo(hits=0, misses=1, maxsize=None, currsize=1)
Bad instance survives del + gc.collect(): True
cached_property instance survives: False
by-value instance survives       : False
by-value cache_info: CacheInfo(hits=0, misses=1, maxsize=128, currsize=1)

What you see: only the instance behind lru_cache on the method survives deletion and a full collection; cached_property and the by-value function let the instance go. The by-value cache holds just numbers.

Why: the cache's key tuple contains self, and the cache is a module-level object that outlives everything.

Leaks

The cache owns every self.

leak.pyruns offline
class Svc:
    @lru_cache(maxsize=None)
    def rate(self, cur):
        return fetch(cur)

Fixed

Cache values, not instances.

fixed.pyruns offline
@lru_cache(maxsize=256)
def _rate(cur):
    return fetch(cur)
class Svc:
    def rate(self, cur):
        return _rate(cur)

The shift: A cache key must not contain objects you expect to be freed. See the bounded-cache idiom.

Land it I explain that self becomes part of the cache key and keeps instances alive, and I cache pure functions by value, use cached_property for per-instance values, and always bound the size.

Likely follow-ups
"How do I choose maxsize?"

From the number of distinct keys you expect to be reused and the memory per entry. Say a typical hour has 5,000 distinct currency-and-date pairs, and each result takes about 200 bytes. A maxsize=8192 cache holds all of them with room to spare.

cache sizingruns offline
8192 entries x 200 bytes = 1,638,400 bytes = about 1.6 MB
(add the keys and the dictionary overhead: budget 2 to 3 times that)

The cache_info() result tells you if the size is right: hits, misses, maxsize and currsize. A low hit ratio, say under 50 %, with a full cache means the size is too small or the keys are too varied (a timestamp in the key means no key repeats).

Never use maxsize=None when keys come from user input. A caller who sends endless different values makes the cache grow without limit, so you have given the outside world control of your memory. A bounded cache loses a little speed, and an unbounded one risks the process.

"Why can the arguments not be lists or dicts?"

The cache is a dictionary keyed on the arguments, so every argument must be hashable (Q5). A list or dict argument fails with TypeError: unhashable type: 'list'. The fix is to convert at the call site, tuple(items) or frozenset(items), or to cache a small function that takes the tuple.

q50_cache.pyruns offline
cache_info: CacheInfo(hits=1, misses=4, maxsize=2, currsize=2)
list argument: unhashable type: 'list'
one(1), one(1.0)            -> entries: 2
two(1, 2), two(1.0, 2)      -> entries: 1
typed: same two calls       -> entries: 2

The second part of the output is about equal values of different types. 1 and 1.0 are equal and hash the same, so two(1, 2) and two(1.0, 2) share one entry, but the single-argument case kept two entries in my run. Which one you get depends on how the key is built, so do not rely on either. If the type changes the result, use typed=True, which keeps them apart in both cases.

The same hash rule is why you cannot cache on an object with __eq__ but no __hash__ (Q22).

"Is lru_cache thread-safe?"

The cache's own bookkeeping is protected, but your function may run twice for the same key. If two threads ask for a key that is not cached at the same moment, both miss, both run the function, and both store a result. For a pure function the second result is the same as the first, so that is harmless. For a function with side effects, it is not.

A different bug appears with asyncio. If you put lru_cache on an async def function, it caches the coroutine object, which can be awaited only once. The second caller gets RuntimeError: cannot reuse already awaited coroutine. Use a cache designed for async code, or cache the result yourself.

On free-threaded builds, the details of locking in functools are version-specific, so check the documentation for yours. My safe rule is to cache only pure functions, and where "run once" is a requirement, add a lock or use a once-per-key design that I control.

"What about invalidation?"

lru_cache has no expiry. It has only cache_clear(), which empties everything, and in recent versions cache_parameters() to read its settings. If results go stale, such as exchange rates that change hourly, you need a policy.

  1. Clear on a schedule: a background job calls cache_clear() each hour. Simple, but everything is cold at once and the next requests all miss together.
  2. Put a time bucket in the key: pass int(time.time()) // 3600 as an argument, so a new hour is a new key and old entries age out through the LRU limit.
  3. Use a TTL cache: cachetools.TTLCache expires each entry after its own time limit.

Staleness is a correctness decision. How wrong may the answer be, and for how long? An invoice that uses a day-old rate may be a legal problem, and a dashboard that is a minute behind is fine. I write the limit in a comment and add a test with a fake clock, so the choice is explicit and not discovered through a wrong invoice.

Drill · Generators and iteration

These questions test whether you can describe a generator as a suspended frame, build constant-memory pipelines, and measure the difference between lists and lazy iteration instead of asserting it.

Q51. "What does yield do to a function's frame?"

Reveal answer

Strong answer Calling a generator function does not run its body. It creates a generator object that owns a fresh frame: the saved state of the function, with its local variables and a pointer to the next instruction. The body starts only at the first next().

When execution reaches yield value, the frame is suspended, not destroyed. The value is handed to the caller, the instruction pointer is saved, and all locals stay alive inside the generator. The next next() resumes right after the yield, with the locals as they were.

When the body ends, or hits return, the generator raises StopIteration and is finished: its frame is released. A normal function's frame dies on return; a generator's frame lives as long as the generator is unfinished.

This is why generators use almost no memory for long sequences (one frame, not a list) and why they are the basis of async coroutines as well.

Picture it The four states of a generator and what the frame holds in each.

The setup: A counter generator, inspected with inspect.getgeneratorstate and its gi_frame.

q51_generator_frame.py · Python 3.14runs offline
import inspect

def counter(n):
    print("    body starts")
    i = 0
    while i < n:
        yield i
        i += 1
    print("    body ends")

g = counter(2)
print("created  :", inspect.getgeneratorstate(g), "| lasti =", g.gi_frame.f_lasti, "(nothing ran yet)")
print("next ->", next(g), "|", inspect.getgeneratorstate(g), "| locals:", g.gi_frame.f_locals)
print("next ->", next(g), "|", inspect.getgeneratorstate(g), "| locals:", g.gi_frame.f_locals)
try:
    next(g)
except StopIteration:
    print("finished :", inspect.getgeneratorstate(g), "| frame is", g.gi_frame)
output · Python 3.14runs offline
created  : GEN_CREATED | lasti = 2 (nothing ran yet)
    body starts
next -> 0 | GEN_SUSPENDED | locals: {'n': 2, 'i': 0}
next -> 1 | GEN_SUSPENDED | locals: {'n': 2, 'i': 1}
    body ends
finished : GEN_CLOSED | frame is None

What you see: nothing prints on creation. After each next the state is GEN_SUSPENDED and the locals (n, i) are still there. After the end the state is GEN_CLOSED and the frame is gone.

Why: the frame object is the generator's memory, kept between calls.

Normal function

Frame dies on return.

func.pyruns offline
def f():
    x = 1
    return x
# x is gone after return

Generator

Frame is suspended.

gen.pyruns offline
def g():
    x = 1
    yield x
    yield x + 1
# x survives between next()

The shift: A generator is a function whose local state is kept between calls.

Land it I say yield suspends the frame with its locals and resumes after it on the next next(), so a generator is a function with memory.

Likely follow-ups
"Does a suspended generator hold resources?"

Yes, for as long as the generator is alive. A suspended generator keeps its frame, and the frame keeps every local variable, so anything those names point to stays in memory. That includes an open file inside a with block, a database cursor or a lock.

The trap is a generator you stop reading half-way. The with inside it has not exited, so the file stays open until the generator is closed or garbage collected. In CPython, dropping the last reference closes it at once, so the problem is often hidden. It shows up when something else still holds a reference, such as a stored traceback or a list of generators, or when you run on another Python implementation.

My rule: if a generator owns a resource, close it deliberately with gen.close() or contextlib.closing(gen). That raises GeneratorExit at the paused yield, and the with block exits right there.

"How big is a generator object?"

It is small, and its size does not depend on how many items it will produce. A generator object is the saved frame plus a little bookkeeping: the local variables, the instruction pointer and the code it belongs to. That is a few hundred bytes plus whatever your locals hold.

Compare the two ways of producing ten million integers. A list holds ten million references, which is about 80 MB for the pointers alone, and the integer objects on top bring it to several hundred megabytes. A generator that computes each number on request holds one counter and one frame, well under a kilobyte. The generator never remembers the numbers it already gave away.

The price is access. You can read the items once, in order, and you cannot ask for the length or jump to item 500. When you need either, build the list. When you only need to walk the data once, the generator is almost free.

"How is this related to coroutines?"

They are the same idea, and the same machinery. An async def coroutine is also a function whose frame can be suspended and resumed. await plays the role of yield: it pauses the frame and hands control back to whoever is driving it. Here the driver is the event loop, not a for loop.

  1. Pause: the coroutine reaches await on something that is not ready, and its frame is suspended with all its locals.
  2. Wait: the event loop runs other tasks while the result is pending.
  3. Resume: when the result arrives, the loop resumes the frame right after the await.

Historically coroutines were built from generators with yield from, which is why the two feel alike. So when someone asks what a task is, the honest answer is: a suspended frame waiting for a result.

"What does return value do in a generator?"

It ends the generator and carries a final value out, attached to the StopIteration exception as e.value. A for loop catches StopIteration silently and throws the value away, so ordinary iteration never sees it.

Code that drives the generator by hand can read it. Code that delegates with yield from receives it as the value of the expression, so result = yield from sub() gets whatever sub returned (Q53). That is how a sub-generator reports a summary, such as a count or a status, after it has finished yielding items.

Two details are worth knowing. A bare return gives None. And in an async generator, return value is a syntax error, because that channel does not exist there.

In everyday code I rarely use it; it matters for delegation and for coroutine frameworks.

Q52 · Scenario. "Process a 20 GB log file on a machine with 512 MB of RAM. Show the pipeline."

Reveal answer

Strong answer Never load the file. Build a pipeline of generators: each stage reads one item from the stage before, does its small job, and passes one item on. Memory stays flat, because at any moment only one line (or a small batch) exists, regardless of file size.

The stages: read (iterate over the open file, which yields one line at a time with an internal buffer), parse (turn the line into a small tuple, skipping bad lines), filter (keep what you need), aggregate (update a counter or running total). The only data kept is the result, which must itself be small: a counter of endpoints, not a list of lines.

Practical details: open in text mode with a fixed encoding and errors="replace"; do not call readlines() or read(); avoid regular expressions per line if a split will do; for CPU-bound parsing, split the file into byte ranges and use a process pool (Q95); compressed logs can be streamed through gzip.open.

To estimate time, measure lines per second on a sample and multiply. Memory is solved by streaming; the remaining question is speed.

Picture it One million synthetic log lines, processed by the list approach and the streaming pipeline, with peak memory measured.

The setup: Generate a log file in a temporary folder, then count slow requests per endpoint two ways.

q52_log_pipeline.py · Python 3.14runs offline
import os, random, tempfile, time, tracemalloc
from collections import Counter

N = 1_000_000
paths = ["/orders", "/price", "/cart", "/menu", "/pay"]

def parse(lines):
    for line in lines:
        parts = line.split()
        if len(parts) == 4:
            yield parts[1], int(parts[3])

def slow_only(rows, limit_ms):
    for path, ms in rows:
        if ms > limit_ms:
            yield path

def streaming(fname):
    with open(fname) as f:
        return Counter(slow_only(parse(f), 400))

def listing(fname):
    with open(fname) as f:
        lines = f.readlines()                         # ❌ TRAP: whole file in memory
    return Counter(slow_only(parse(lines), 400))

with tempfile.TemporaryDirectory() as d:
    fname = os.path.join(d, "access.log")
    rnd = random.Random(1)
    with open(fname, "w") as f:
        for i in range(N):
            f.write(f"{i} {rnd.choice(paths)} 200 {rnd.randint(1, 500)}\n")
    print(f"file size: {os.path.getsize(fname) / 1e6:.1f} MB for {N:,} lines")
    for label, fn in (("readlines()", listing), ("streaming  ", streaming)):
        tracemalloc.start()
        t = time.perf_counter()
        result = fn(fname)
        secs = time.perf_counter() - t
        peak = tracemalloc.get_traced_memory()[1]
        tracemalloc.stop()
        print(f"{label}: peak {peak / 1e6:7.1f} MB, {secs:5.2f} s, slow total {sum(result.values()):,}")
output · Python 3.14runs offline
file size: 21.1 MB for 1,000,000 lines
readlines(): peak    70.7 MB,  2.16 s, slow total 199,515
streaming  : peak     0.2 MB,  2.05 s, slow total 199,515
# measured on the course machine; 1M lines instead of 20 GB; your numbers will differ

What you see: both give the same answer; the list version peaks at about 70 MB for a 21 MB file (over three times the file size) while the streaming version peaks at 0.2 MB. Scale the same ratio to 20 GB and the list version needs roughly 65 GB, far beyond 512 MB, while the streaming version stays flat.

Why: a file object is itself a lazy iterator over lines, so generator stages never need more than the current line.

Load everything

Memory grows with the file.

load.pyruns offline
lines = open(f).readlines()
rows = [parse(l) for l in lines]
# 20 GB file -> MemoryError

Pipeline

Memory stays flat.

pipe.pyruns offline
rows = parse(open(f))
slow = slow_only(rows, 400)
counts = Counter(slow)

The shift: Replace "read, then process" with "process each line as it is read".

Land it I chain generators (read, parse, filter, aggregate) so one line is in memory at a time, keep only a small aggregate, and estimate runtime from measured lines per second.

Likely follow-ups
"How long would 20 GB take?"

I would measure it on a sample, then multiply. Time a run over a few million lines, divide to get lines per second, then scale to the full file. The run above took about 2 s per million lines (with tracemalloc switched on, so a little pessimistic).

time estimateruns offline
20,000,000,000 bytes / 21 bytes per line = 952 million lines
952 million lines x 2 s per million      = 1,904 s = about 32 min
same file at 200 bytes per line          = 100 million lines (if the 2 s/M held, 200 s)

The lines in that test average 21 bytes, which is shorter than most real log lines. Real logs are often 150 to 300 bytes per line, so the same 20 GB holds far fewer lines, but each line costs more to split and parse. That is why measuring on your own file beats the arithmetic.

If one core is too slow, split the file into byte ranges, give each range to a process in a pool, and merge the small counters at the end (Q95). Start each range at the next newline so no line is cut in two. Four to eight processes usually bring a half-hour job down to minutes.

"What if the aggregate does not fit either?"

Then I need a bounded structure, because a plain dictionary grows with the number of distinct keys. The right choice depends on how many keys there are and how exact the answer must be.

  1. Only the top N: keep a heap of size N and drop the rest. Memory is N entries, whatever the input size.
  2. Approximate answers: a Count-Min sketch estimates counts, and HyperLogLog estimates how many distinct values there are, each in a few kilobytes with a small known error.
  3. Exact answers: write sorted partial results to disk and merge them (an external sort), or let SQLite or DuckDB aggregate from a file. Both can run within a memory limit.

First check the cardinality, meaning the number of distinct keys. Five endpoints fit anywhere. Five hundred million user ids do not, and I would say so before building anything.

"How do I handle bad lines?"

I make the parse stage tolerant, so one bad line cannot kill a job that has run for hours. A malformed line is counted and skipped, or written to a reject file, and the pipeline moves on.

Two kinds of bad input need different handling. The first is a line that does not match the format, such as a truncated write at the end of a rotated file. The parse step catches that case, increments a counter, and continues. The second is a byte sequence that is not valid text. Opening the file with an explicit encoding and errors="replace" turns each bad byte into a replacement character instead of raising UnicodeDecodeError.

At the end I log the reject count and a few sample lines. If rejects are a tiny fraction, I carry on. If they are ten percent of the file, the format assumption is wrong, and that is a finding, not noise.

"Is a generator pipeline slower than a list?"

Slightly, yes. Every item passes through several generator resumes, one per stage, and each resume costs tens of nanoseconds. A list-based version that does the same work in one loop avoids some of that.

In exchange you get three things. Output begins at once, rather than after the whole file is read. Memory stays flat, so the machine never swaps, and swapping is far slower than any generator overhead. And each stage is a small function you can test alone. On small data the difference is not measurable. On a 20 GB file the list version simply does not run, so the comparison is moot.

If a profile shows that stage overhead matters, process in batches: itertools.batched (Q57) gives tuples of, say, 10,000 lines, and one stage handles a whole tuple per call. That keeps memory bounded and removes most resumes.

Q53. "What does yield from delegate, exactly?"

Reveal answer

Strong answer yield from sub hands control to the sub-iterator for the duration. The outer generator yields each value the sub-iterator produces, directly to the caller, without writing a loop. It is shorthand for for x in sub: yield x, plus three things the loop version does not do.

First, values sent in with send() go straight to the sub-generator. Second, exceptions thrown in with throw() and close() are forwarded to it. Third, the value of the expression yield from sub is the sub-generator's return value, so a sub-generator can finish with return result and the outer one receives it.

Typical uses: flattening nested structures recursively, splitting a long generator into named parts, and (historically) writing coroutines. In modern code you meet it mainly in tree traversal and composition of generators.

Picture it Delegation with a return value, and a recursive flatten.

The setup: A sub-generator that yields two values and returns a total; an outer generator that uses it; then a nested-list flatten.

q53_yield_from.py · Python 3.14runs offline
def inner():
    yield 1
    yield 2
    return "inner finished"

def outer():
    result = yield from inner()          # delegates; result is inner's return value
    print("  outer got:", result)
    yield 3

print("values:", list(outer()))

def loop_version():
    for x in inner():                    # the long way: return value is lost
        yield x

g = loop_version()
print("loop version:", list(g))

def flatten(items):
    for item in items:
        if isinstance(item, list):
            yield from flatten(item)
        else:
            yield item

print("flatten:", list(flatten([1, [2, [3, 4]], 5])))
output · Python 3.14runs offline
  outer got: inner finished
values: [1, 2, 3]
loop version: [1, 2]
flatten: [1, 2, 3, 4, 5]

What you see: yield from produced 1, 2 and then 3, and the outer generator received inner finished; the loop version cannot see it. The recursive flatten works with no accumulator list.

Why: yield from is a delegation, not a copy: the caller talks to the inner generator through the outer one.

Land it I say yield from delegates to a sub-iterator, forwarding values, send, throw, close and returning the sub-generator's result, which a plain for loop cannot do.

Likely follow-ups
"Why not just use a for loop?"

For plain iteration, you can. for x in sub: yield x and yield from sub give the same items, and yield from is shorter and a little faster because the loop runs in C. The difference appears when the outer generator is more than a pipe.

Three things only yield from does. It forwards send() values straight into the sub-generator. It forwards throw() and close() too, so the sub-generator can run its own cleanup. And it gives you the sub-generator's return value as the value of the expression.

A hand-written loop that tries to copy all this needs a try around every yield, special handling of GeneratorExit, and a manual catch of StopIteration to fetch the result. Almost everyone gets one of those wrong. So I use a plain loop when I only read values, and yield from the moment a caller might send, throw or want a result.

"How does recursion depth behave in the flatten example?"

Every nested level adds one generator frame to the chain, so recursion depth equals nesting depth. Python's recursion limit (1,000 by default, Q65) therefore applies. Data nested a few levels deep is fine. Data nested thousands of levels deep raises RecursionError.

There is a second cost: a value yielded from depth d passes up through d generators on its way out. CPython optimises yield from chains somewhat, but the work still grows with depth. For shallow structures such as a menu with categories and items, nobody will notice.

For data whose depth you do not control, such as user-supplied JSON, I would use an explicit stack: a list of iterators, push on entering a nested list, pop when one runs dry. It is still lazy and still yields items one at a time, but it uses a heap list instead of the call stack, so depth is bounded only by memory.

"Does yield from accept any iterable?"

Yes, any iterable. yield from calls iter() on the object and hands out its items, so lists, tuples, strings, ranges, dicts, file objects and other generators all work. Only a real generator receives send and throw calls through it; for the others it just iterates.

That makes it handy for combining sources inside one generator:

sources.py
def everything(path):
    yield from range(3)            # 0, 1, 2
    yield from "ab"                # "a", "b" (strings give characters)
    with open(path) as f:
        yield from f               # one line at a time

This is also the clean way to write a generator that reads several inputs in a fixed order, such as a header block, then a body, then a footer, without any loop variables or temporary lists.

The trap is the string case. yield from "abc" yields three one-character strings, not one string of three characters. If you meant to emit the whole string, write yield "abc". The same goes for a dict, which yields its keys, not its pairs.

"What replaced yield from for coroutines?"

The answer is await. Before Python 3.5, coroutines were generators decorated with @asyncio.coroutine and written with yield from. The 3.5 syntax async def and await replaced that, and the old decorator was removed in 3.11.

The mechanism is the same one: the current frame pauses, control passes to the thing being awaited, and when that finishes its result becomes the value of the expression. That is exactly what yield from does with a sub-generator's return value.

Why change the syntax? Two reasons. A coroutine and a generator now look different, so a reader (and a type checker) knows which is which. And await is only legal inside async def, so you cannot accidentally mix up the two. This also explains the rule that you cannot call await from an ordinary function: there is no suspendable frame there to pause.

Q54. "What are send(), throw() and close() on a generator for?"

Reveal answer

Strong answer They turn a generator into a two-way channel. send(value) resumes the generator and makes the paused yield expression evaluate to value; it returns the next yielded item. Before the first send, you must prime it with next() or send(None).

throw(exc) raises an exception inside the generator at the paused yield, so the generator can catch it, clean up, or yield a recovery value. close() throws GeneratorExit at the paused yield; the generator should not yield again, and its finally blocks run, which is how it releases resources.

These are the primitives that coroutines were built on. In everyday code you need them rarely: close() matters most, because abandoned generators are closed (by garbage collection) and their finally blocks run. send appears in running accumulators and old-style coroutines, and throw in schedulers and testing.

If you catch GeneratorExit, always re-raise it or return; yielding after it raises RuntimeError.

Picture it A running average fed by send, an error injected with throw, and cleanup by close.

The setup: One generator that receives numbers, handles a ValueError and cleans up when closed.

q54_send_throw_close.py · Python 3.14runs offline
def averager():
    total, count = 0.0, 0
    try:
        while True:
            try:
                value = yield (total / count if count else None)
            except ValueError as e:
                print("  inside generator, caught:", e)
                continue
            total += value
            count += 1
    finally:
        print("  cleanup: averager closing after", count, "values")

avg = averager()
next(avg)                                  # prime: run to the first yield
print("send 10 ->", avg.send(10))
print("send 20 ->", avg.send(20))
print("throw   ->", avg.throw(ValueError("bad reading")))
print("send 30 ->", avg.send(30))
avg.close()
print("closed")
output · Python 3.14runs offline
send 10 -> 10.0
send 20 -> 15.0
  inside generator, caught: bad reading
throw   -> 15.0
send 30 -> 20.0
  cleanup: averager closing after 3 values
closed

What you see: the averager keeps running state between calls, accepts values through send, survives the injected ValueError, and its finally block runs on close().

Why: the generator frame is suspended at the yield; each method resumes it with a value or an exception at that exact point.

Land it I say send pushes a value into the suspended yield, throw raises inside it, and close raises GeneratorExit so finally runs, and I rely mostly on close for cleanup.

Likely follow-ups
"Why must I prime the generator first?"

Because a brand-new generator is not paused at any yield. It has not started, so there is no yield expression waiting to receive your value. The first next() runs the body up to the first yield, and only then is there somewhere to put a value.

That is why the first call must carry no payload: next(g) or g.send(None). Sending a real value to an unstarted generator raises TypeError, with a message saying you can only send None to a just-started generator.

  1. Create: g = averager() builds the object; nothing runs yet.
  2. Prime: next(g) runs to the first yield and stops.
  3. Use: now g.send(10) delivers 10 to that paused yield and returns the next yielded value.

Older coroutine code hid step two behind a small decorator. Today I just call next once, with a comment.

"What happens if I forget to close a generator?"

In CPython, usually nothing bad. When the last reference to a generator disappears, the interpreter calls its close() for you. That raises GeneratorExit at the paused yield, and the finally blocks and with exits inside the generator run (Q11). It is deterministic because CPython counts references.

It breaks down in three cases. On other implementations such as PyPy, collection happens later, at an unpredictable time. If something keeps a reference alive, such as a stored traceback or a global list, the generator stays suspended and its resources stay open. And in an async generator, cleanup needs the event loop, so the same problem is harder.

My habit for any generator that holds a file, a lock or a connection: use contextlib.closing (or aclosing for async), so the cleanup point is visible in the code and not left to the garbage collector.

"Is this still used in modern Python?"

Rarely by hand, but the mechanisms are alive inside the standard library. async/await replaced coroutines built from generators, so send is no longer how most people write concurrent code.

Where it survives:

  1. send: running accumulators, push-style parsers and simulations, where a generator keeps state between values you push in.
  2. throw: contextlib.contextmanager. When the body of your with block raises, the library calls throw() on the generator, so the exception appears at the yield and your try/finally or except there can handle it (Q25).
  3. close: everywhere, silently, whenever a generator is dropped.

So you use these primitives daily without writing them. In an interview I would say that, and then show the one place I would write send myself: a small running-average generator.

"Can I get the return value after close?"

Yes, since Python 3.13, and only if the generator catches GeneratorExit and then returns a value. In 3.12 and earlier close() always returned None. Here is the same script on both versions:

q54_close_value.pyruns offline
def acc():
    total = 0
    try:
        while True:
            total += yield
    except GeneratorExit:
        return total

g = acc()
next(g)
g.send(5)
g.send(7)
print("close() returned:", g.close())
output
3.12:  close() returned: None
3.14:  close() returned: 12

So the generator catches GeneratorExit, which close() raises at the paused yield, and returns the running total instead of re-raising. On 3.12, that return value was thrown away. On 3.13 and later, close() hands it back to the caller, which is handy for a final tally after an early stop. Without that rule, you would need a separate attribute or a callback to get the total out.

I would not depend on it unless the project pins 3.13 or later. The portable way to get a final value is StopIteration.value or yield from.

Q55. "List comprehension versus generator expression — memory and speed, measured."

Reveal answer

Strong answer A list comprehension [f(x) for x in data] builds the whole list in memory immediately. A generator expression (f(x) for x in data) builds nothing: it produces one item per request. The bracket type decides.

Memory: the list needs space for every result at once; the generator needs a constant amount. For ten million integers that is hundreds of megabytes against a few hundred bytes.

Speed: it depends on the workload. A generator pays a small cost per item to suspend and resume its frame, so on small data a list can be as fast or faster. When the list is huge, allocating it costs time too, and the generator can win, as in the run below.

For a single pass over data you will not keep, the generator wins on memory and has no startup delay. If you need to index, take len, or iterate twice, you need the list. Use a generator expression as the argument to sum, any, all, max, min, "".join where only one pass is needed.

Measure on your data. The sections below show real numbers.

Picture it Memory for a million items, and time for ten million, both ways.

The setup: Sum of squares, once with sum([...]) and once with sum(...).

q55_listcomp_vs_genexp.py · Python 3.14runs offline
import time, tracemalloc, sys

N_MEM = 1_000_000
for label, make in (("list comprehension", lambda: [x * x for x in range(N_MEM)]),
                    ("generator expression", lambda: (x * x for x in range(N_MEM)))):
    tracemalloc.start()
    obj = make()
    cur, _ = tracemalloc.get_traced_memory()
    tracemalloc.stop()
    print(f"{label:21} object holds {cur / 1e6:6.2f} MB (sys.getsizeof {sys.getsizeof(obj):,} B)")

N = 10_000_000
for label, fn in (("sum([x*x ...])", lambda: sum([x * x for x in range(N)])),
                  ("sum(x*x ...)  ", lambda: sum(x * x for x in range(N)))):
    t = time.perf_counter()
    total = fn()
    print(f"{label} over {N:,}: {time.perf_counter() - t:5.2f} s   total={total}")

tracemalloc.start()
sum([x * x for x in range(2_000_000)])
peak_list = tracemalloc.get_traced_memory()[1]
tracemalloc.reset_peak()
sum(x * x for x in range(2_000_000))
peak_gen = tracemalloc.get_traced_memory()[1]
print(f"peak while summing 2M: list {peak_list / 1e6:.1f} MB, generator {peak_gen / 1e6:.3f} MB")
output · Python 3.14runs offline
list comprehension    object holds  40.45 MB (sys.getsizeof 8,448,728 B)
generator expression  object holds   0.00 MB (sys.getsizeof 208 B)
sum([x*x ...]) over 10,000,000:  0.84 s   total=333333283333335000000
sum(x*x ...)   over 10,000,000:  0.61 s   total=333333283333335000000
peak while summing 2M: list 81.1 MB, generator 0.004 MB
# measured on the course machine; your numbers will differ

What you see: the list holds tens of megabytes for a million items while the generator holds almost nothing; over ten million items the generator was faster here (0.61 s against 0.84 s) because it never allocated ten million integers, and the peak memory differs by a huge factor. On smaller inputs the two are close.

Why: the list pays memory up front; the generator pays a small cost per item for suspending and resuming.

Eager

Everything built now.

eager.pyruns offline
total = sum([x * x for x in nums])
# list of N squares exists

Lazy

One item at a time.

lazy.pyruns offline
total = sum(x * x for x in nums)
# no list at all

The shift: When the data is consumed once, drop the brackets and let sum pull the values.

Land it I choose a generator expression for one-pass consumers, a list when I need indexing, length or a second pass, and I quote measured numbers rather than assuming one is faster.

Likely follow-ups
"When is a list comprehension faster?"

When the list is small enough to stay in the CPU cache, and the consumer is cheap. A list comprehension runs a tight loop inside the interpreter that appends each result with one instruction (LIST_APPEND). A generator expression has to suspend and resume its frame once per item, which costs a few tens of nanoseconds each time.

Python 3.12 made comprehensions faster again by inlining them into the calling function (PEP 709). Before that, each list comprehension created and called a hidden function.

The other side is that building a huge list is not free either: allocating, growing and later freeing hundreds of megabytes costs time, which is why the generator won in the 10-million run above. So there is a crossover, and it depends on size and on what you do with the items. For ordinary code the gap is small noise, so I choose on memory and clarity, and measure only when a profile points here.

"When is a generator expression a trap?"

The main trap is that a generator expression is not a snapshot. It reads the source lazily, at the moment each item is pulled. If the data changes between creating it and consuming it, you see the changed data. A list comprehension takes its snapshot immediately.

A second, subtler rule: only the first iterable is evaluated at creation. Everything else, including names from the surrounding scope, is looked up late:

late binding
n = 2
g = (x * n for x in range(3))   # range(3) evaluated now; n is not
n = 10
print(list(g))                  # [0, 10, 20], not [0, 2, 4]

The third trap is iterating twice (Q23): the second pass gets nothing, with no error. The output above is the real result from running it, and it surprises people who expect the value at creation time.

When a bug looks like this, I turn the expression into a list and inspect it in a debugger. Then I decide whether the laziness is worth keeping.

"What about any and all?"

They are the best use of the lazy form, because both stop as soon as the answer is known. any returns True at the first truthy item. all returns False at the first falsy one. With a generator expression, the work stops at that same point.

Compare the two spellings on a million items where the first item already matches:

  1. Generator: any(x > 100 for x in data) tests one item, returns True, and builds nothing.
  2. List: any([x > 100 for x in data]) first tests all million items and builds a million-element list of booleans, and only then any looks at it.

That is a factor of a million in work for the best case, and a big memory saving in every case. The same applies to next(x for x in data if cond(x)) for finding the first match. The bracket-less form also reads cleanly when a generator expression is the only argument.

"And dict or set comprehensions?"

Same trade-off, with the eager side only. A dict comprehension {k: f(v) for k, v in items} and a set comprehension {f(x) for x in data} build the whole container immediately. There is no lazy dict or set comprehension.

Two notes. There is no tuple comprehension: (x for x in data) is a generator expression, and the tuple spelling is tuple(x for x in data). And for dicts, a later key silently overwrites an earlier one, so a dict comprehension over data with duplicate keys keeps only the last value for each.

When the output is huge, the question is whether you need a container at all. If you only write the results out, write them to a file or a database as you go, and let the generator feed the writer. A dict of ten million entries is gigabytes, while the streamed version stays flat. I build a dict or set only when I need fast lookup afterwards.

Q56 · Scenario. "itertools.groupby returned the same key in several separate groups. Why?"

Reveal answer

Strong answer groupby groups consecutive items with the same key. It does not sort and it does not look ahead. When the key changes it closes a group and starts a new one, so if equal keys are scattered through the input, the same key appears in several groups.

That makes it work on a single pass with constant memory, like the shell's uniq. It is the opposite of a SQL GROUP BY or collections.defaultdict, which collect all items of a key wherever they are.

Fixes. Sort first by the same key function: groupby(sorted(data, key=k), key=k). That needs the data in memory (or an external sort). Use a defaultdict(list) to collect in one pass, when the result fits in memory. Use a Counter if you only need counts. Use groupby unsorted only when the input is known to be clustered, such as a file already sorted by customer.

A second trap: each group is itself a lazy iterator that shares the underlying stream. If you advance to the next group, the previous one is gone. Turn groups into lists (list(g)) as you go.

Picture it The same orders grouped three ways.

The setup: Five orders for two customers in mixed order.

q56_groupby.py · Python 3.14runs offline
from itertools import groupby
from collections import defaultdict

orders = [("ana", 10), ("bob", 5), ("ana", 7), ("bob", 3), ("ana", 1)]
key = lambda o: o[0]

print("unsorted groupby:")
for k, g in groupby(orders, key=key):                 # ❌ TRAP: ana appears three times
    print("  ", k, [amount for _, amount in g])

print("sorted first:")
for k, g in groupby(sorted(orders, key=key), key=key):
    print("  ", k, [amount for _, amount in g])

by_customer = defaultdict(list)                        # ✅ one pass, any order
for name, amount in orders:
    by_customer[name].append(amount)
print("defaultdict:", dict(by_customer))

groups = [g for _, g in groupby(sorted(orders, key=key), key=key)]
print("groups kept as iterators, read later:", [list(g) for g in groups])
output · Python 3.14runs offline
unsorted groupby:
   ana [10]
   bob [5]
   ana [7]
   bob [3]
   ana [1]
sorted first:
   ana [10, 7, 1]
   bob [5, 3]
defaultdict: {'ana': [10, 7, 1], 'bob': [5, 3]}
groups kept as iterators, read later: [[], []]

What you see: unsorted input yields ana three times and bob twice; sorting or a defaultdict fixes it. The last line shows the other trap: groups saved as iterators are empty by the time you read them.

Why: groupby only compares each item with the one before it, and its groups share the single underlying iterator.

SQL / defaultdict

Collects all matches.

collect.pyruns offline
by = defaultdict(list)
for k, v in rows:
    by[k].append(v)

groupby

Only neighbours.

adjacent.pyruns offline
for k, g in groupby(rows, key):
    use(k, list(g))
# needs sorted input

The shift: groupby is "run-length grouping", not "group by". See Q57 for where it fits.

Land it I say groupby only merges adjacent equal keys, so I sort first, use a defaultdict when order is unknown, and consume each group before moving on.

Likely follow-ups
"When is groupby the right tool?"

When the data is already ordered by the key, and there is a lot of it. Typical cases are a log file sorted by customer, the result of a database query with ORDER BY, or the output of merging several sorted files. In each, equal keys really are neighbours, so groupby is correct.

It then gives you one group at a time with constant memory. You process a group, move on, and never hold more than one group. A dictionary-based approach would hold every group at once.

A good pairing is heapq.merge, which merges several already-sorted streams lazily, followed by groupby on the same key. Together they group many large sorted files without loading any of them.

The rule I apply in review: groupby is fine when a comment or a visible sorted or ORDER BY shows that the input is ordered. If the order is only an accident of how the data arrived, I replace it with a dictionary.

"What does sorting cost?"

Sorting costs O(n log n) time, and it needs all n items in memory at once, because you cannot sort a stream you have not finished reading. For ten million small records that can be gigabytes, and the sort is the slow step.

The alternatives differ in what they hold:

  1. defaultdict(list): one pass, O(n) time, but it still holds every item, just grouped.
  2. Counter or running totals: one number per key. If you only need counts or sums, this is the cheapest by far, since memory grows with the number of keys and not the number of items.
  3. Database or DuckDB: let it do the grouping from disk when the data is larger than memory.

So I ask what the result must contain. Sums and counts need no grouping at all. Full lists per key need the memory. Here is the small proof of the failure and of the fix:

q56_groupby_scattered.pyruns offline
unsorted: [('a', 1), ('b', 1), ('a', 1)]
sorted:   [('a', 2), ('b', 1)]
"Why does list(g) matter?"

Because each group is not a list. It is a lazy iterator that reads from the same shared stream as the outer groupby. When the loop moves on to the next key, the shared stream advances, and the earlier group object becomes invalid. It is empty if you look at it later.

The classic bug is collecting groups for later use:

stale groups
groups = {k: g for k, g in groupby(sorted(data))}   # every g is already spent
groups = {k: list(g) for k, g in groupby(sorted(data))}   # correct

The first version looks right and gives dictionary values that are empty or only partly filled, with no error. The second consumes each group inside the loop body, at the moment it is live.

So the rule is: use the group inside the loop iteration that produced it, or turn it into a list or a sum right there. Never store the iterator.

"How would I catch this in a test?"

I would test with input where equal keys are separated, because that is the one shape the bug needs. Something like ["a", "b", "a"] must give two groups for "a" unless you sort. Then I assert one group per distinct key on the production path. A test with already-clustered data such as ["a", "a", "b"] passes with and without the bug, so it proves nothing.

Property-based testing (Q138) finds this quickly. The property is: for any shuffled list, the grouped result equals a dictionary-based reference. Hypothesis generates shuffled input, finds the scattered case in seconds, and shrinks it to the shortest failing example, often just three items.

Beyond tests, a review rule helps: any groupby must have a visible sorted(...) with the same key function, or a comment naming why the input is already ordered. That one rule catches most real cases before they run.

Q57. "Which itertools functions earn their place in production code?"

Reveal answer

Strong answer Seven I use regularly. islice(it, n) takes the first n items of any iterator, or a slice of it, without a list. chain(a, b) and chain.from_iterable(list_of_lists) concatenate sources lazily. batched(it, n) (3.12+) yields tuples of up to n items: the standard way to send bulk inserts or API calls in chunks. pairwise(it) (3.10+) yields neighbouring pairs, for diffs and deltas. groupby for clustered data (Q56). accumulate for running totals. zip_longest to pair sequences of unequal length.

Honourable mentions: product for parameter grids, combinations for small searches, count as a thread-friendly counter, cycle and repeat. And a warning: tee splits one iterator into several, but buffers every item that one copy has consumed and another has not, so memory grows if they drift apart. If you need two passes, store a list.

The theme: these functions work on any iterable, one item at a time, so they compose into the pipelines of Q52 without building lists.

Picture it Each function on tiny data, and the memory cost of tee.

The setup: Short examples plus a tee where one branch races ahead.

q57_itertools.py · Python 3.14runs offline
from itertools import islice, chain, batched, pairwise, accumulate, zip_longest, tee, count

def numbers():
    n = 0
    while True:                         # an infinite source
        n += 1
        yield n

print("islice      :", list(islice(numbers(), 5)), "| items 3..5:", list(islice(numbers(), 2, 5)))
print("chain       :", list(chain([1, 2], (3,), "ab")))
print("batched(3)  :", list(batched(range(8), 3)))
print("pairwise    :", list(pairwise([100, 130, 125, 160])), "-> deltas", [b - a for a, b in pairwise([100, 130, 125, 160])])
print("accumulate  :", list(accumulate([5, 3, 8, 1])))
print("zip_longest :", list(zip_longest([1, 2, 3], "ab", fillvalue="-")))
print("count       :", list(islice(count(10, 5), 4)))

a, b = tee(range(1_000_000))
consumed = sum(1 for _ in a)             # a runs to the end first
print("tee: a consumed", consumed, "items; b has not started, so tee buffered them all")
print("tee: b still yields", next(b), next(b), "...")
output · Python 3.14runs offline
islice      : [1, 2, 3, 4, 5] | items 3..5: [3, 4, 5]
chain       : [1, 2, 3, 'a', 'b']
batched(3)  : [(0, 1, 2), (3, 4, 5), (6, 7)]
pairwise    : [(100, 130), (130, 125), (125, 160)] -> deltas [30, -5, 35]
accumulate  : [5, 8, 16, 17]
zip_longest : [(1, 'a'), (2, 'b'), (3, '-')]
count       : [10, 15, 20, 25]
tee: a consumed 1000000 items; b has not started, so tee buffered them all
tee: b still yields 0 1 ...

What you see: each helper does one small job on a stream; islice works even on an infinite source, batched returns tuples with a short last batch, and tee has to remember a million items for the lagging copy.

Why: these tools take and return iterators, so they never hold more than they must, except tee, which buffers by design.

Manual

Index arithmetic.

manual.pyruns offline
for i in range(0, len(xs), 100):
    chunk = xs[i:i + 100]
    save(chunk)      # xs must be a list

itertools

Any iterable.

tools.pyruns offline
for chunk in batched(rows, 100):
    save(chunk)      # rows can be a stream

The shift: batched replaces slicing arithmetic and works on streams that have no length.

Land it I name islice, chain, batched, pairwise, groupby, accumulate and zip_longest as the everyday set, and I warn that tee buffers and groupby needs sorted input.

Likely follow-ups
"What was there before batched?"

People wrote a small helper, usually with islice. The common one-liner was iter(lambda: tuple(islice(it, n)), ()): it takes n items at a time and stops when it gets an empty tuple. Others wrote a four-line generator with a loop.

Python 3.12 added itertools.batched(it, n), and 3.13 added a strict=True option that raises an error if the final batch is short. On older versions, copy the recipe from the itertools documentation. Here is the behaviour on 3.14:

q57_batched_strict.pyruns offline
[(0, 1, 2), (3, 4, 5), (6,)]
strict: batched(): incomplete batch

Batching is worth knowing because many systems have per-call costs or limits: a database bulk insert, an SQS call that takes ten messages, a Kafka produce batch, or a rate-limited API that accepts 100 ids per request. One call per item is slow; one call per batch is fast and still memory-bounded.

"Why does islice not support negative indices?"

Because an iterator may be endless, or one-way, and it cannot know where its end is without reading to it. A negative index such as "the last 3 items" would force islice to consume the whole stream first, which defeats the purpose and never finishes on an infinite one.

For "the last n items" use a bounded deque instead: collections.deque(it, maxlen=n). It reads the whole stream once, but it keeps only the most recent n items and drops older ones as new ones arrive.

last_n.py
from collections import deque
last3 = list(deque(range(1_000_000), maxlen=3))   # [999997, 999998, 999999]

Time is linear in the stream length, as it must be, and memory is only n items. That is the honest cost of the question. If the data is a list, plain slicing data[-3:] is better, since a list does know its length.

"How does accumulate differ from reduce?"

The difference is what you get back. functools.reduce folds a sequence into one final value. itertools.accumulate yields every intermediate result as it goes, so it is the right tool for running totals, running maximums and balances after each transaction.

With amounts 100, -30, 50, accumulate gives 100, 70, 120, and reduce with addition gives only 120. If I want the total alone, I would write sum(amounts). It is clearer and faster than reduce for addition. I use reduce only for folds that sum, min, max or math.prod cannot do, such as merging a list of dictionaries.

Both take a function, and accumulate has an initial= option (3.8+) to start from a value and emit it first. Because accumulate is lazy, it works on streams: you can write each running balance to a file without holding the series.

"When is tee acceptable?"

When the consumers stay close together, so the buffer stays small. Think of two adjacent pipeline steps that read the same stream at nearly the same pace, such as one counting items while the other writes them. tee only has to remember items that one copy has seen and the other has not.

The cost grows with the gap. If copy A reads a million items before copy B reads any, tee holds a million items in memory. In the worst case, it behaves like a list you did not know you had, and the saving is gone.

  1. Lockstep consumers: use tee; the buffer stays tiny.
  2. Independent or slow consumer: write the data once to a list or a file, or run the pipeline twice from the source.
  3. Threads: the copies are not thread-safe, so do not give them to different threads.

When in doubt, I store a list if it fits, because that is honest about the memory.

Q58. "Python generators versus Java Streams — what is the same and what differs?"

Reveal answer

Strong answer Same: both are lazy: nothing is computed until a consumer pulls items. Both work in a pipeline of stages (map, filter, limit) one element at a time, with no intermediate collection. Both are single use: after a stream has been consumed, using it again fails (Java) or yields nothing (Python).

Different: a Java stream is built from operations declared up front and runs only when a terminal operation (collect, forEach, count) is called. A Python generator is a function with a suspended frame; it runs when anyone calls next, and you can write arbitrary code in it.

Java streams offer parallel execution (parallelStream); Python generators are sequential. Java reuse fails loudly with IllegalStateException; Python reuse fails silently with nothing (Q23). Python generators can also receive values (send) and be suspended and resumed as coroutines; Java streams cannot.

Python's stream-like tools are generator expressions, map, filter and itertools. They are less fluent to chain than .stream().map().filter(), and you read them inside-out or through named stages.

Picture it Proof of laziness: the stages interleave item by item, and a second use gives nothing.

The setup: Three generator stages that print when they handle an item.

q58_generators_vs_streams.py · Python 3.14runs offline
def source():
    for n in (1, 2, 3):
        print(f"  source yields {n}")
        yield n

def double(items):
    for n in items:
        print(f"  double handles {n}")
        yield n * 2

def keep_big(items):
    for n in items:
        print(f"  keep_big checks {n}")
        if n > 2:
            yield n

pipeline = keep_big(double(source()))
print("pipeline built, nothing printed yet")
print("--- first result")
print("got", next(pipeline))
print("--- the rest")
print("got", list(pipeline))
print("--- second use")
print("got", list(pipeline))
output · Python 3.14runs offline
pipeline built, nothing printed yet
--- first result
  source yields 1
  double handles 1
  keep_big checks 2
  source yields 2
  double handles 2
  keep_big checks 4
got 4
--- the rest
  source yields 3
  double handles 3
  keep_big checks 6
got [6]
--- second use
got []

What you see: each item travels through all stages before the next item starts, the first result appears after reading only the first two items, and a second use returns an empty list.

Why: every stage pulls from the one before it on demand, so the work is interleaved and nothing is computed ahead of need.

Java · Spring

Streams.

Pipe.javaruns offline
var out = source.stream()
  .map(n -> n * 2)
  .filter(n -> n > 2)
  .toList();   // terminal op runs it

Python

Generators.

pipe.pyruns offline
out = [n for n in
       (n * 2 for n in source)
       if n > 2]    # list() pulls

The shift: Java declares a pipeline and fires it with a terminal operation; Python's pipeline runs whenever something calls next.

Land it I say both are lazy and single-use pipelines, Java's fire at a terminal operation and can run in parallel, Python's are suspended frames that can also receive values, and reuse fails loudly in Java and silently in Python.

Likely follow-ups
"Can Python run a generator pipeline in parallel?"

Not by itself. A generator runs on one thread, one item at a time, and nothing in a pipeline of generators is parallel. To use several cores you split the work yourself.

The usual shape is to cut the input into chunks, send each chunk to a worker through concurrent.futures.ProcessPoolExecutor (or multiprocessing), and combine the partial results. Each worker can use a generator pipeline inside its own chunk. For CPU-bound work, processes are the standard answer because of the GIL (Q75). The free-threaded build can let threads help (Q79), and 3.14's InterpreterPoolExecutor is a third option.

Java hides this behind parallelStream(), which splits the source and runs on a shared fork-join pool. That is convenient and has its own pitfalls: the pool is shared with the rest of the program, ordering can surprise you, and blocking calls inside it starve other work.

In Python the parallelism is explicit, which is more typing but fewer surprises.

"What happens if an exception occurs midway?"

In both, the exception travels back toward the consumer, and the work stops.

  1. Python: the exception is raised inside the stage that failed. It propagates out of that generator's next() call, through every stage above it, and out of the consuming for loop. The generator that raised is finished, and later next() calls on it give StopIteration.
  2. Java: the terminal operation, such as collect, throws, and the stream cannot be reused.

The part people forget is cleanup. A pipeline that was only half consumed may still hold a file, a connection or a lock. In Python, close the generator with close() or put the consumer in a with contextlib.closing(...) block. In Java, a stream backed by a resource, such as Files.lines, must be closed with try-with-resources.

So the rule is the same in both languages: whoever owns the resource owns the cleanup, even when the pipeline fails.

"Do Python generators allow short-circuiting?"

Yes, naturally, because laziness and short-circuiting are the same thing: you stop pulling. next(pipeline) asks for exactly one result and the stages do only the work needed for it. any, all, and itertools.islice stop early in the same way.

Java has direct equivalents: findFirst, limit, anyMatch, allMatch and noneMatch. A pipeline of filter and map followed by findFirst processes elements one at a time and stops at the first that survives.

Both depend on the source being lazy. If the first stage is readlines() in Python, or a source that has already loaded a full List in Java, the whole data is already in memory before the first stage runs, and short-circuiting saves only the later work. For large files, read through a lazy iterator, such as the file object itself, or Files.lines in Java.

"Which is more readable for long pipelines?"

For a long pipeline, Java's fluent chain wins, because you read it left to right in the order the data flows: .stream().filter(...).map(...).collect(...). Python's generator expressions nest inside-out, so the first step is the innermost one, and a four-stage pipeline written as nested calls is hard to read.

The Python fix is to name every stage. Write each as a small function or assign it to an intermediate variable, in the order of the data:

named_stages.py
lines = open_log(path)
parsed = (parse(x) for x in lines)
wanted = (r for r in parsed if r.status >= 500)
counts = Counter(r.endpoint for r in wanted)

Nothing runs until the last line pulls the data through all the stages, one item at a time, so the memory stays flat even for a very large log.

This reads top to bottom, and each stage can be tested alone and given a debugger breakpoint. Libraries such as toolz and more-itertools add a fluent feel, but plain named generators are the idiom most teams expect.

Q59. "cache, lru_cache, cached_property, partial, singledispatch — one real use for each."

Reveal answer

Strong answer functools.cache (3.9+): remember results of a pure function with a small, fixed set of inputs, such as parsing a config template or building a regex for a given pattern. Unbounded, so only for bounded input sets. lru_cache(maxsize=N): the same, with a size cap and least-recently-used eviction, for something like an exchange-rate lookup keyed by currency and day. cached_property: compute an attribute on first access and keep it on the instance, such as a parsed price table built from raw data.

partial(func, *args): fix some arguments in advance to make a callback with fewer parameters, such as partial(reprice, tenant) for a scheduler (Q43) or partial(round, ndigits=2). singledispatch: choose an implementation by the type of the first argument, replacing an isinstance ladder, for example to_json(obj) handling Decimal, datetime, UUID separately and open for extension by registering new types.

Each has a catch. The caches need hashable arguments, keep results alive, and never expire. cached_property needs an instance __dict__ (no plain __slots__). partial objects are not functions (no __name__). singledispatch dispatches on the first argument only (singledispatchmethod for methods).

Picture it One tiny example of each, with cache_info() as evidence.

The setup: A rate lookup, a price table property, a bound callback and a type-based formatter.

q59_functools_tools.py · Python 3.14runs offline
import functools
from decimal import Decimal
from datetime import date

calls = {"rate": 0, "table": 0}

@functools.lru_cache(maxsize=2)
def rate(currency):
    calls["rate"] += 1
    return {"EUR": 1.08, "GBP": 1.27, "JPY": 0.0067}[currency]

for c in ("EUR", "EUR", "GBP", "JPY", "EUR"):
    rate(c)
print("lru_cache:", rate.cache_info(), "| real lookups:", calls["rate"])

@functools.cache
def fee_schedule(tier):
    return {"gold": 0, "basic": 3}[tier]
fee_schedule("gold"); fee_schedule("gold")
print("cache    :", fee_schedule.cache_info())

class Menu:
    def __init__(self, raw):
        self.raw = raw
    @functools.cached_property
    def table(self):
        calls["table"] += 1
        return dict(item.split("=") for item in self.raw.split(","))

m = Menu("a=1,b=2")
m.table; m.table
print("cached_property computed", calls["table"], "time ->", m.table)

def reprice(tenant, factor):
    return f"{tenant} x{factor}"
acme = functools.partial(reprice, "acme")
print("partial  :", acme(1.1), "|", acme.func.__name__, acme.args)

@functools.singledispatch
def to_json(value):
    return str(value)
@to_json.register
def _(value: Decimal):
    return f"{value:.2f}"
@to_json.register
def _(value: date):
    return value.isoformat()
print("dispatch :", to_json(Decimal("2.5")), to_json(date(2026, 11, 24)), to_json(7))
output · Python 3.14runs offline
lru_cache: CacheInfo(hits=1, misses=4, maxsize=2, currsize=2) | real lookups: 4
cache    : CacheInfo(hits=1, misses=1, maxsize=None, currsize=1)
cached_property computed 1 time -> {'a': '1', 'b': '2'}
partial  : acme x1.1 | reprice ('acme',)
dispatch : 2.50 2026-11-24 7

What you see: with maxsize=2, the rotation EUR, GBP, JPY evicts EUR so the last EUR call looks it up again (5 calls, 4 misses, 1 hit); cached_property computed once; partial fixes the first argument; singledispatch picked the right branch for each type.

Why: each tool is a small wrapper around a function that either stores results or fixes how it is called.

Type ladder

Edit it for every new type.

ladder.pyruns offline
def to_json(v):
    if isinstance(v, Decimal):
        return f"{v:.2f}"
    elif isinstance(v, date): ...

singledispatch

Register per type.

disp.pyruns offline
@to_json.register
def _(v: Decimal):
    return f"{v:.2f}"
# new types add themselves

The shift: Dispatch by type replaces a growing isinstance chain with registrations that live next to each type.

Land it I give one use each: cache for fixed input sets, lru_cache for bounded lookups, cached_property for per-instance values, partial for callbacks, singledispatch for type-based behaviour, and I state each one's catch.

Likely follow-ups
"What is the difference between cache and lru_cache?"

The only difference is the size limit. functools.cache(f) is the same as lru_cache(maxsize=None)(f): it never evicts anything, so it stores one entry for every distinct argument it has ever seen. Because it needs no eviction bookkeeping, it is slightly faster.

lru_cache(maxsize=N) keeps at most N entries and, when full, throws away the least recently used one. The default maxsize is 128.

The decision is about where the arguments come from. If the inputs come from a small, known set, such as the pattern names in a config file, an unbounded cache is safe and simple. If the inputs come from outside, such as user ids, URLs or request parameters, an unbounded cache is a memory leak that grows with traffic (Q50, Q112). For those, I choose a bounded lru_cache and check cache_info() for the hit rate, because a cache with a poor hit rate costs memory and gives nothing back.

"Does cached_property work with threads?"

Mostly yes, with one change you should know about. cached_property stores its result in the instance's __dict__ on the first access, and later reads find it there.

Before Python 3.12 it also took a lock, shared by the whole class, while computing. That prevented double computation but meant a slow computation on one instance blocked every other instance of the class. Python 3.12 removed that lock.

So on 3.12 and later, two threads that read the property at the same moment may both compute it. One result is stored, and the other is discarded or overwritten. The value is still consistent, but the function body ran twice.

That is harmless if the computation is pure and cheap to repeat. It is a problem if it has side effects, such as opening a connection, charging a counter or calling a paid API. For those cases I use my own lock, or compute the value in __init__. Check the documentation for your exact version.

"Why use partial rather than a lambda?"

Mainly because of three practical differences. A partial object can be inspected, it can be pickled, and it does not have the late-binding trap.

  1. Introspectable: p.func, p.args and p.keywords show what it wraps, which helps in logs and tests.
  2. Picklable: a partial of a module-level function can be sent to a worker process (Q73). A lambda cannot be pickled by name.
  3. Binds now: the arguments are captured when you create it. A lambda such as lambda: reprice(tenant) looks up tenant when it is called, which gives the classic loop bug (Q43).

A lambda is fine for a short one-off callback that stays in-process. One catch: a partial has no __name__, so a logger that prints fn.__name__ fails. Use functools.update_wrapper to copy the name across, or log p.func.__name__.

"Does singledispatch work on methods or on second arguments?"

Not directly, on both counts. singledispatch picks the implementation from the type of the first positional argument, and nothing else. On an instance method, the first argument is self, so it would always dispatch on the class of the object, which is not what you want.

For methods, use functools.singledispatchmethod (3.8+), which dispatches on the first argument after self. For dispatch on two arguments, you have three honest options: a dictionary keyed by a tuple of types, a small chain of match statements with class patterns, or the third-party multipledispatch package.

It does respect inheritance. If you register an implementation for a base class, every subclass uses it unless a more specific registration exists. For example, registering Number would cover int and float through the abstract-class hierarchy. That makes it a clean replacement for an isinstance ladder, and callers can add new types by registering, without editing the original function.

Q60 · Design. "Design a lazy, paginated API-client iterator that fetches pages on demand and retries failures."

Reveal answer

Strong answer The caller wants for order in client.orders(since="2026-11-01"): and does not want to know about pages. So I write a generator that fetches one page, yields its items, then fetches the next page only when the caller asks for more.

Design decisions. Cursor or page number: prefer the server's cursor/token (stable under inserts); fall back to offsets only if that is all there is. Stop condition: the server says there is no next cursor, or returns an empty page. Laziness: nothing is fetched until the first next; if the caller stops after three items, no further page is requested.

Retries: around each page request, not around the whole iteration, with capped exponential backoff and jitter for transient errors (Q48); never retry client errors such as 400. Timeouts: every request has one. Resumability: expose the cursor so a crashed job can restart where it stopped. Rate limits: honour Retry-After and slow down on 429. Resources: use one session for the whole iteration and close it when the generator ends (try/finally).

Make the HTTP call injectable so tests use a fake client with scripted failures.

Picture it A fake API with three pages and one flaky page, and a count of the requests actually made.

The setup: Page 2 fails once with a timeout. The client yields items lazily and retries only that page.

q60_paginated_client.py · Python 3.14runs offline
class FakeApi:
    def __init__(self):
        self.requests = []
        self.failed_once = False
    def get_page(self, cursor):
        self.requests.append(cursor)
        if cursor == "p2" and not self.failed_once:
            self.failed_once = True
            raise TimeoutError("page p2 timed out")
        pages = {None: ([1, 2, 3], "p2"), "p2": ([4, 5, 6], "p3"), "p3": ([7, 8], None)}
        return pages[cursor]

def fetch_with_retry(api, cursor, attempts=3):
    for n in range(attempts):
        try:
            return api.get_page(cursor)
        except TimeoutError as e:
            if n == attempts - 1:
                raise
            print(f"    retrying cursor={cursor!r} after: {e}")

def iter_orders(api, start_cursor=None):
    cursor = start_cursor
    while True:
        items, cursor_next = fetch_with_retry(api, cursor)
        yield from items                      # page items one by one
        if cursor_next is None:
            return
        cursor = cursor_next

api = FakeApi()
orders = iter_orders(api)
print("created, requests so far:", api.requests)
first_three = [next(orders) for _ in range(3)]
print("took", first_three, "-> requests:", api.requests)
rest = list(orders)
print("took the rest", rest, "-> requests:", api.requests)

api2 = FakeApi()
it = iter_orders(api2)
for item in it:
    if item == 2:
        break
it.close()
print("stopped early at item 2 -> requests:", api2.requests)
output · Python 3.14runs offline
created, requests so far: []
took [1, 2, 3] -> requests: [None]
    retrying cursor='p2' after: page p2 timed out
took the rest [4, 5, 6, 7, 8] -> requests: [None, 'p2', 'p2', 'p3']
stopped early at item 2 -> requests: [None]

What you see: nothing is requested at creation; three items need only the first page; the second page fails once and is retried; breaking out early never fetches pages 2 or 3.

Why: the generator suspends after yielding the last item of a page and fetches only when next needs more.

Eager

Download everything first.

eager.pyruns offline
def all_orders(api):
    out = []
    while cursor is not None:
        out += page(api, cursor)
    return out

Lazy

Fetch pages on demand.

lazy.pyruns offline
def iter_orders(api):
    while True:
        items, cur = page(api, cur)
        yield from items

The shift: A generator turns "download all pages" into "download the next page when someone asks".

Land it I write a generator over a cursor, retry each page with capped backoff and jitter, never fetch beyond what the caller consumes, close the session in finally, and make the client injectable for tests.

Likely follow-ups
"How do I make it resumable?"

Treat the cursor as the state of the job, and save it after each completed page, not after each item. Saving it every item is a lot of writes and gains little. When the job restarts, pass the saved cursor as start_cursor and continue.

There is one rule that makes this correct: processing must be idempotent. If the job crashes after handling 40 of 100 items on a page, the saved cursor still points to the start of that page, so the restart repeats those 40. If repeating them causes duplicates, you need a unique key, an upsert, or a record of processed ids.

To expose the cursor, a bare generator is not enough, because the caller cannot read its local variables. Write a small class with __iter__, __next__ (or an internal generator) and a public cursor attribute that updates after each page. The caller reads it.cursor at page boundaries and stores it wherever the job keeps its progress.

"What about parallel page fetching?"

It depends on the pagination style. A cursor chain is sequential by nature: you only learn page 3's cursor from page 2's response, so you cannot request pages 2 and 3 at once. Parallelism needs a different split.

If the API supports offset or date-range pagination, you can fetch several pages concurrently with a bounded pool, for example four requests in flight. The costs are real: results may arrive out of order, an insert during the walk can shift offsets and cause duplicates or gaps, and you will meet rate limits sooner.

A safer middle step is prefetching. While the caller processes page N, a background task already fetches page N+1. Only one extra page is ever in flight, memory stays bounded at about two pages, and order and cursor semantics are untouched. For many jobs the processing time is comparable to the fetch time, so this nearly halves the total time.

I would only go beyond that after measuring that fetching, not processing, is the bottleneck.

"How do I test it?"

With a fake API that I control: it records every request it receives and fails on a schedule I script, such as "second request fails twice, then succeeds". I inject the fake client and a fake sleep, so the tests are fast and deterministic.

  1. Laziness: creating the iterator makes zero requests, and the first next makes exactly one.
  2. Partial use: taking 3 items from a page of 100 makes one request, not more.
  3. Retries: a transient failure is retried and the sleeps follow the expected backoff, while a 400 is not retried.
  4. Exhaustion and cleanup: after the last allowed attempt the error is raised, and closing the iterator early stops all fetching.

A short runnable check of the first two points:

q60_cursor_walk.pyruns offline
requests before first next: 0
[1, 2, 3, 4] requests so far: 2
"Async version?"

Yes, and the structure is the same. Use an async def generator, which has yield inside, and consume it with async for. Each page request becomes an awaited call, and the retry delay uses await asyncio.sleep(...) instead of time.sleep, which would block the whole event loop.

Three things deserve care. First, cleanup: an async generator's finally block needs the event loop to run, so abandoning it half-way is riskier than with a normal generator. Wrap it in contextlib.aclosing, so the session is closed when the consumer stops early, whether by break or by an exception. Second, use one shared async HTTP client for the whole walk, not one per page. Third, put a timeout on every request, for example with asyncio.timeout.

Once it is async, prefetching the next page becomes easy: start the next fetch as a task before yielding the current page, and await it afterwards.

Drill · Bytecode and the interpreter

These questions test whether you can describe what CPython does to your source before and while it runs, and read real dis output instead of guessing at performance.

Q61. "What happens between typing python app.py and the first line of your code running?"

Reveal answer

Strong answer Roughly eight steps, and most of them are about getting a clean interpreter, not your code. 1. The OS starts the python binary. 2. The runtime initialises: memory allocators, the built-in types, sys, builtins, and the import machinery. 3. It reads settings: command-line flags, environment variables (PYTHONPATH, PYTHONUTF8), and finds the standard library and the virtual environment (via pyvenv.cfg, Q126).

4. The site module is imported: it adds site-packages to sys.path, processes .pth files and can run start-up hooks. 5. sys.path[0] is set to the folder of the script. 6. The script file is read and compiled to a code object (source, tokens, tree, bytecode, Q62). 7. A module named __main__ is created and the code runs inside its namespace. 8. Your first line executes.

Two practical consequences. Interpreter start-up costs roughly ten to twenty milliseconds on its own, so tiny commands run by the thousand (git hooks, CLI tools) feel slow. And whatever is on sys.path[0] is searched first, so a file named random.py or json.py beside your script shadows the standard library.

Picture it What is already loaded before your first line, and how long the bare start-up takes.

The setup: A script that reports its own state, then asks a fresh interpreter to import nothing and prints the five most expensive start-up imports.

q61_startup.py · Python 3.14runs offline
import subprocess, sys, time

print("__name__          :", __name__)
print("sys.path[0]       :", sys.path[0].replace(sys.path[0], "<script folder>"))
print("modules already loaded:", len(sys.modules), "| 'site' loaded:", "site" in sys.modules, "| 'json' loaded:", "json" in sys.modules)
print("stdlib folder     :", [p for p in sys.path if p.endswith("python3.14")][0].split("/")[-1])

t = time.perf_counter()
r = subprocess.run([sys.executable, "-X", "importtime", "-c", "pass"], capture_output=True, text=True)
print(f"bare 'python -c pass' took {(time.perf_counter() - t) * 1000:.0f} ms")
rows = []
for line in r.stderr.splitlines()[1:]:
    parts = line.split("|")
    rows.append((int(parts[1]), parts[2].strip()))
for cumulative, name in sorted(rows, reverse=True)[:5]:
    print(f"  {cumulative:6} us  {name}")
output · Python 3.14runs offline
__name__          : __main__
sys.path[0]       : <script folder>
modules already loaded: 61 | 'site' loaded: True | 'json' loaded: False
stdlib folder     : python3.14
bare 'python -c pass' took 13 ms
    2293 us  site
    1633 us  os
    1388 us  encodings
     990 us  _frozen_importlib_external
     721 us  _collections_abc
# measured on the course machine; your numbers will differ

What you see: before line 1, 61 modules are already loaded and site is among them; the bare interpreter start took about 13 ms here, and -X importtime names the heaviest start-up imports.

Why: the interpreter must be a working Python before it can run you, and site and the codec and import modules are part of that.

Java · Spring

JVM start, then classloading.

Start.txtruns offline
java -jar app.jar
 JVM starts (~40 ms)
 loads classes lazily
 main() runs

Python

Interpreter, site, then compile.

start.txtruns offline
python app.py
 runtime + site (~20 ms)
 compile app.py to bytecode
 __main__ runs

The shift: Both pay a runtime start-up first; Python then compiles your script (but caches imported modules as .pyc, Q64) before running it.

Land it I list the start-up steps (runtime init, site, sys.path[0], compile, create __main__, run) and note that script-folder shadowing and start-up cost are the practical consequences.

Likely follow-ups
"Why is a file called random.py dangerous?"

Because Python puts the script's own folder first on the module search path, ahead of the standard library. sys.path[0] is that folder. So when anything runs import random, the finder checks your folder first, finds your random.py, and stops. The real one is never reached.

The damage spreads past your own code. Libraries that import random internally get your file too, and they fail in confusing ways, often with a message about a "partially initialised module" or a missing attribute such as random.randint. You may be looking at a traceback inside a library you did not write.

I avoid any file name that matches a standard module: json, email, types, test, logging, queue, string. If you hit the symptom, print module.__file__ to see which file was actually imported. Recent Python versions add a hint to the error message when this happens, and Ruff has a rule that flags such file names.

"What is a .pth file, and why mention it?"

A .pth file is a plain text file in site-packages. When the site module runs at start-up, it reads each one. Every line that is a directory path is added to sys.path, and every line starting with import is executed as code.

It matters for two reasons. Editable installs (pip install -e) use them to point Python at your source folder. And they run on every interpreter start, so a slow or broken one taxes every command, including python --version style tiny scripts, and is easy to forget.

To find the cause of a slow start, split the problem:

  1. Skip site: python -S -c pass starts without it. If that is much faster, the cost is in site or .pth files.
  2. See imports: python -X importtime -c pass lists what was imported and how long each took.
  3. Look inside: open the .pth files in site-packages and read the import lines.
"How do python -m pkg and python script.py differ?"

The difference is what goes first on the path and whether the file is treated as part of a package.

  1. python script.py: sys.path[0] is the folder containing the script. The file runs as __main__ with no package context, so a relative import such as from . import util fails.
  2. python -m pkg.mod: sys.path[0] is the current working directory. The module is found through the normal import system and runs as __main__ but knows its package, so relative imports work.

This is also why a script placed inside a package and run by path behaves differently from the same code run with -m. The first breaks on imports and can shadow modules next to it; the second resolves everything from the project root.

My rule is to use -m for anything that lives inside a package. python -m pytest and python -m uvicorn app.main:app then import the same way every time, whichever directory you started from.

"Can I make start-up faster?"

Yes, but the trick is to do less, not to do it faster. Python's own start-up is small. On this machine it was about 13 ms (Q61). The seconds come from imports and import-time work.

Several levers, from cheapest:

  1. Import less at start: do not import a heavy library in a module that every command loads.
  2. Import lazily: move heavy imports inside the function that needs them, or use lazy import in 3.15 (Q74).
  3. No work at import time: no file reads, network calls or big table builds at module level.
  4. Keep the cache writable: so .pyc files are created and reused (Q64).

A long-running server pays start-up once, so shaving it rarely matters there. It matters for CLI tools, git hooks, serverless functions and tests, which start the interpreter many times.

Always measure first with python -X importtime, then fix the biggest line, then measure again.

Q62. "Read this dis output and explain each instruction."

Reveal answer

Strong answer dis shows the bytecode: the instructions of CPython's virtual machine. It is a stack machine: instructions push values on a stack, pop them, and push results. Reading it means following the stack.

For a function price(qty, unit, rush=False) computing total = qty * unit, adding 5 if rush, and returning it, expect these groups. Loads (LOAD_FAST, LOAD_SMALL_INT, LOAD_CONST) push a local variable or constant. BINARY_OP pops two values, applies the operator named in brackets and pushes the result. STORE_FAST pops the top and stores it in a local slot. TO_BOOL and POP_JUMP_IF_FALSE implement the if: convert to bool, jump over the body if false. RETURN_VALUE pops and returns.

The left column is the source line, the column of numbers with L1-style labels marks jump targets, and the number beside an instruction is its argument (a slot index or constant) with the meaning in brackets. Exact opcode names change between versions (3.14 has LOAD_FAST_BORROW, 3.13 did not), so read the principle, and the output of your own version.

Picture it A real listing on 3.14, annotated line by line below it.

The setup: The price function and dis.dis.

q62_read_dis.py · Python 3.14runs offline
import dis

def price(qty, unit, rush=False):
    total = qty * unit
    if rush:
        total += 5
    return total

dis.dis(price)
output · Python 3.14runs offline
  3           RESUME                   0

  4           LOAD_FAST_BORROW_LOAD_FAST_BORROW 1 (qty, unit)
              BINARY_OP                5 (*)
              STORE_FAST               3 (total)

  5           LOAD_FAST_BORROW         2 (rush)
              TO_BOOL
              POP_JUMP_IF_FALSE       10 (to L1)
              NOT_TAKEN

  6           LOAD_FAST_BORROW         3 (total)
              LOAD_SMALL_INT           5
              BINARY_OP               13 (+=)
              STORE_FAST               3 (total)

  7   L1:     LOAD_FAST_BORROW         3 (total)
              RETURN_VALUE

What you see: line 4 loads qty and unit (the two LOAD_FAST_BORROW forms push borrowed references without a reference-count write), BINARY_OP (*) multiplies, and STORE_FAST total saves the result. Line 5 loads rush, TO_BOOL converts it, and POP_JUMP_IF_FALSE skips line 6's addition when false. Line 6 loads total and 5, does BINARY_OP (+=) and stores. Line 7 loads total and RETURN_VALUE returns it.

Why: each source line becomes a handful of stack operations; the compiler has already decided that every name is a fast local.

Source

What you wrote.

src.pyruns offline
total = qty * unit
if rush:
    total += 5
return total

Bytecode

What the VM runs.

vm.txtruns offline
LOAD qty, unit
BINARY_OP *
STORE total
LOAD rush; JUMP_IF_FALSE
LOAD total, 5; BINARY_OP +=
RETURN total

The shift: Python source is compiled to a small stack-machine program before it runs; dis lets you see it.

Land it I read dis as a stack machine: loads push, BINARY_OP pops two and pushes one, STORE pops into a local, jumps implement if, and I check exact names on my own version.

Likely follow-ups
"Why does Python use a stack machine?"

Because a stack machine is the simplest design to compile to and to interpret. The operands of an instruction are not named: BINARY_OP just takes the top two values from the stack. That keeps each instruction tiny, and the compiler needs no register allocator, which is the hard part of generating code for a register machine.

A register machine, like Lua's virtual machine or Android's old Dalvik, names its operands inside each instruction. It needs fewer instructions for the same work but each one is wider and harder to produce. CPython's authors chose simplicity, and from 3.11 on they recover speed with specialisation (Q63) rather than by changing the machine model.

The Java virtual machine is also a stack machine. So a Java engineer reading dis output will recognise the style at once: loads push, operators pop two and push one, and stores pop into a slot. The same reading skill transfers between javap -c and dis.

"What is RESUME at the top?"

RESUME is a marker at the start of a function. It does nothing that your program can see. The interpreter uses it as a place to check for tracing and debugging events, and to count how many times the function has run, so that the specialiser knows when the code is warm (Q63).

It is one of a few instructions that exist for the machine, not for your logic. Another is CACHE. After many instructions, such as LOAD_ATTR or CALL, a few empty slots are reserved in the bytecode. When the specialiser learns something, for example the version of a class or the position of an attribute, it stores that there. dis hides them by default and shows them with show_caches=True.

The practical advice is to skip them when reading. Look at the loads, the BINARY_OP, the jumps and the return, which carry the meaning of the function. Use the caches only when you are studying how specialisation works.

"How do I use dis in practice?"

I use it to settle questions with evidence, instead of arguing from memory. It is a magnifying glass for what the compiler really did.

Examples where it answers a real question:

  1. Folding: does 60 * 60 * 24 compute at run time? dis shows a single LOAD_CONST 86400, so no.
  2. Atomicity: is x += 1 one step? It is several instructions (load, add, store), which is why threads can interleave in it (Q78).
  3. Scopes: does a comprehension have its own frame? Not since 3.12, because it is inlined.
  4. Errors: why does UnboundLocalError happen? The function uses LOAD_FAST for a name that is assigned later in the same function (Q41).

What I do not do is offer micro-optimisation advice from instruction counts. Fewer instructions are not always faster, because specialised ones differ in cost. Timings decide (Q68).

"Is bytecode portable and stable?"

No. Bytecode is an implementation detail of CPython, and it changes with almost every minor release. Opcodes are added, renamed and removed. For example 3.14 introduced LOAD_FAST_BORROW, which 3.13 does not have.

That is why .pyc files start with a magic number tied to the interpreter version. If you try to load a file compiled by another version, Python sees the mismatch, ignores it and recompiles from source (Q64). The same file is simply not valid across versions.

Three practical consequences. Do not ship .pyc files as a distribution format and expect them to run on a different Python. Do not write tools that parse bytecode without pinning the Python version they support. And if you use a tool that does depend on it, such as a coverage tool, a debugger or a decompiler, expect to upgrade it with each Python release.

The portable form is the source, or a wheel built for the version you run.

Q63. "What is the specialising adaptive interpreter (3.11+), and what does "quickening" mean?"

Reveal answer

Strong answer Python is dynamically typed, so a * b could mean int times int, float times float, string repetition, or a custom __mul__. The generic instruction has to check the types every time. The specialising adaptive interpreter (PEP 659, Python 3.11) watches the instructions as they run, and when one keeps seeing the same types, it rewrites that instruction in place to a specialised version, such as BINARY_OP_MULTIPLY_INT, that has the type check built in and skips the general lookup.

Quickening is that warm-up: after a function has run a small number of times (the counters are tiny, a few runs for hot paths), its bytecode is replaced by the adaptive and then specialised forms. If the types change later, a guard fails, the instruction de-optimises back and re-specialises for the new types.

The effect: Python 3.11 was reported as 10 to 60 percent faster than 3.10, about 25 percent on average, and later versions keep adding specialisations. Attribute access, global lookups, calls and for loops are all specialised. Consequences for you: write ordinary, monomorphic code (same types at the same place); hot code that sees one type is faster than code that sees many.

Picture it The same function before and after it warms up with ints, and again after floats.

The setup: dis.dis(f, adaptive=True) shows the specialised instructions; the function is called 2,000 times with each type.

q63_quickening.py · Python 3.14runs offline
import dis

def f(a, b):
    return a * b + a

def show(title):
    print(f"--- {title}")
    for ins in dis.get_instructions(f, adaptive=True):
        if ins.opname.startswith("BINARY_OP"):
            print(f"   {ins.opname:26}{ins.argrepr}")

show("cold (just defined)")
for i in range(2000):
    f(i, 3)
show("after 2,000 calls with ints")
for i in range(2000):
    f(1.5, 2.5)
show("after 2,000 calls with floats")
for i in range(2000):
    f("ab", 2)
show("after strings (str * int, then str + str)")
output · Python 3.14runs offline
--- cold (just defined)
   BINARY_OP                 *
   BINARY_OP                 +
--- after 2,000 calls with ints
   BINARY_OP_MULTIPLY_INT    *
   BINARY_OP_ADD_INT         +
--- after 2,000 calls with floats
   BINARY_OP_MULTIPLY_FLOAT  *
   BINARY_OP_ADD_FLOAT       +
--- after strings (str * int, then str + str)
   BINARY_OP                 *
   BINARY_OP_ADD_UNICODE     +

What you see: the plain BINARY_OP becomes BINARY_OP_MULTIPLY_INT and BINARY_OP_ADD_INT, then flips to the _FLOAT forms when the types change. With strings, the multiplication stays generic BINARY_OP (no specialised string-times-int form) while the + specialises to BINARY_OP_ADD_UNICODE.

Why: each specialised instruction carries a cheap type guard; when the guard fails often enough, the interpreter re-specialises or gives up.

Java · Spring

JIT compiles hot methods.

Jit.txtruns offline
interpret -> profile
hot method -> machine code
(C1, C2 compilers)

Python

Hot instructions rewritten.

spec.txtruns offline
BINARY_OP
-> BINARY_OP_MULTIPLY_INT
(still bytecode, no machine
code; JIT is experimental)

The shift: HotSpot compiles hot methods to machine code; CPython 3.11+ stays an interpreter but rewrites hot bytecode into type-specific forms.

Land it I explain that CPython watches hot instructions and rewrites them in place into type-specialised versions (quickening), guarded and reversible, which is why monomorphic code is faster.

Likely follow-ups
"Does it make Python as fast as Java?"

No, and the gap is still large. The specialising interpreter removes a lot of waste from the interpreter loop, so typical code on 3.11 and later is noticeably faster than on 3.10, about 25 percent on average. It does not change the basic model.

Several things stay slow. Every value is still a full object with a header and a reference count, so a number is not a machine word. The interpreter still decodes and dispatches each instruction one by one. And without the experimental JIT, there is no general machine-code compiler in the default build. A Java JIT can compile a hot numeric loop into native code that works on raw values, and a loop over ints in CPython can still be tens of times slower.

So the honest summary is: faster Python, same kind of language. For heavy numeric work you still move the loop out of Python into NumPy, Cython, numba or Rust (Q108, Q109), or you use PyPy if your libraries allow it.

"What types of instruction are specialised?"

The specialiser covers the operations that appear in almost every hot loop. Roughly, by group:

  1. Arithmetic and comparison: BINARY_OP and COMPARE_OP for ints, floats and strings.
  2. Attribute and name lookup: LOAD_ATTR for instance attributes, slots, class attributes, modules and properties, plus LOAD_GLOBAL for globals and builtins, and STORE_ATTR.
  3. Calls: CALL for Python functions, builtins and methods.
  4. Loops and indexing: FOR_ITER over lists, tuples and ranges, and BINARY_SUBSCR on lists, tuples and dicts.

The exact list changes with each release, as new specialisations are added and a few are merged, so I do not memorise it. To see it for your interpreter, run dis.dis(f, adaptive=True) after calling the function a few times and read the names that appear, or check the documentation for your version.

"How would the specialiser punish bad code?"

It punishes code that is polymorphic at a hot spot, meaning the same line sees different types. Specialisation bets that what it saw last time will happen again. If a function receives an int, then a float, then a Decimal, the guard fails repeatedly, the instruction de-optimises and re-specialises, and eventually it settles on the generic slow path. The program is still correct, only slower.

A second case is instance layout. Instances that get their attributes in different orders, or that gain attributes outside __init__, have different internal shapes, so cached attribute positions miss.

The advice is cheap to follow:

  1. Same types: keep hot functions monomorphic where it is natural, and convert at the edge.
  2. Same layout: assign every attribute in __init__, in the same order, and avoid adding attributes later.

I would not contort the design for this. I would apply it inside the few functions a profile has proved hot.

"Is this the same as the JIT?"

No. They are two separate layers, and it is a common point of confusion. The specialising adaptive interpreter (3.11+) is on by default. It still executes bytecode, one instruction at a time, only with better instructions that have type checks built in.

The experimental JIT (3.13+, Q66) is a different step. It translates sequences of hot, already-specialised instructions into machine code, removing the dispatch overhead between them. It builds on the specialiser's work: it needs the type-specialised instructions as its input.

  1. Specialisation: default, no switch, safe to rely on.
  2. JIT: optional, needs a build with JIT support, switched on with PYTHON_JIT=1, gains modest and reported rather than promised.

In an interview I say that plainly, and add that I would measure the JIT on my own workload before enabling it anywhere.

Q64. "When are .pyc files reused, and when are they regenerated?"

Reveal answer

Strong answer When you import a module, CPython compiles its source to bytecode and writes the result to __pycache__/name.cpython-314.pyc next to it, so the next import can skip compiling. The script you run directly (python app.py) is not cached; only imported modules are.

On import Python checks the .pyc header. By default (timestamp-based) the header stores the source file's modification time and size; if they match the current source, the .pyc is reused, otherwise the module is recompiled and the .pyc rewritten.

The header also contains a magic number tied to the Python version, so a .pyc from another version is ignored. Hash-based .pyc files (PEP 552) store a hash of the source instead; with checked they re-hash the source on import and with unchecked they trust the file blindly, which suits reproducible builds and read-only deployments.

Regeneration also happens if the cache folder is missing, and nothing is written if the folder is read-only (the program still works, just compiles at each start). PYTHONDONTWRITEBYTECODE or -B disables writing. In containers, pre-compile at build time (python -m compileall) so the first request does not pay.

Picture it A module imported, reloaded unchanged, then edited, with the .pyc header decoded.

The setup: A temporary module on sys.path; the script watches the .pyc file's modification time.

q64_pyc.py · Python 3.14runs offline
import importlib, importlib.util, os, py_compile, struct, sys, tempfile

def header(pyc):
    h = open(pyc, "rb").read(16)
    flags, mtime, size = struct.unpack("<III", h[4:16])
    return flags, mtime, size

with tempfile.TemporaryDirectory() as d:
    sys.path.insert(0, d)
    src = os.path.join(d, "rules.py")
    open(src, "w").write("print('  rules.py body runs')\nRATE = 1\n")
    import rules
    pyc = importlib.util.cache_from_source(src)
    print("cache file :", os.path.basename(pyc), "| exists:", os.path.exists(pyc))
    flags, mtime, size = header(pyc)
    print("header     : flags =", flags, "(0 = timestamp-based) | source size recorded =", size, "| matches:", size == os.path.getsize(src))
    first = os.stat(pyc).st_mtime_ns

    importlib.reload(rules)
    print("reload, source unchanged -> pyc rewritten?", os.stat(pyc).st_mtime_ns != first)

    open(src, "w").write("print('  rules.py body runs')\nRATE = 2   # edited, longer file\n")
    importlib.reload(rules)
    print("reload, source edited    -> pyc rewritten?", os.stat(pyc).st_mtime_ns != first, "| RATE =", rules.RATE)
    print("header size now matches new source:", header(pyc)[2] == os.path.getsize(src))

    py_compile.compile(src, pyc, invalidation_mode=py_compile.PycInvalidationMode.CHECKED_HASH)
    print("checked-hash pyc flags:", header(pyc)[0], "(3 = hash-based, checked)")
output · Python 3.14runs offline
  rules.py body runs
cache file : rules.cpython-314.pyc | exists: True
header     : flags = 0 (0 = timestamp-based) | source size recorded = 39 | matches: True
  rules.py body runs
reload, source unchanged -> pyc rewritten? False
  rules.py body runs
reload, source edited    -> pyc rewritten? True | RATE = 2
header size now matches new source: True
checked-hash pyc flags: 3 (3 = hash-based, checked)

What you see: the first import creates rules.cpython-314.pyc, an unchanged reload leaves it alone, an edit rewrites it and the header records the new size, and a checked-hash .pyc has flags 3 instead of 0.

Why: the header is a cheap fingerprint of the source; matching fingerprint means skip compiling.

Java · Spring

Compile step, then ship.

Build.txtruns offline
javac Svc.java -> Svc.class
(done before deploy)

Python

Compile on first import.

py.txtruns offline
import svc -> svc.py compiled
__pycache__/svc.cpython-314.pyc
(or: compileall at build)

The shift: Java compiles ahead of time; Python compiles lazily on first import and caches, unless you compile during the build.

Land it I say imported modules are compiled once and cached as .pyc keyed by timestamp-and-size or by source hash and Python version, the main script is never cached, and I pre-compile in container builds.

Likely follow-ups
"Should I commit .pyc files or __pycache__?"

No. Add __pycache__/ and *.pyc to .gitignore. These files are build artefacts: Python regenerates them by itself the first time a module is imported, and they are tied to one Python version (the file name even carries it, as in cpython-314).

Committing them causes real trouble. A teammate on a different Python version gets files that are ignored and rewritten, so the repository shows constant changes. Timestamp-based files also record the source file's modification time, and a fresh git clone gives every file a new time, so the committed .pyc would be rejected as stale anyway. You carry noise and gain nothing.

The exception is deliberate: a pre-compiled, hash-based .pyc in a built container image or inside a zipapp, produced by the build pipeline for a known interpreter version. Even then it is a build output of the image, not something checked into source control.

"Does a .pyc make the program faster?"

It makes start-up faster, and it does not make running code faster. The .pyc file holds the bytecode, so on import Python skips reading, tokenising, parsing and compiling the source. After that, the code runs exactly the same as it would after a fresh compile.

How much it saves depends on the module size. Compiling a 5,000-line module takes tens of milliseconds. For a service that starts once and runs for days, that gain is invisible. For a tool started thousands of times a day, a serverless function with cold starts, or a test run that launches many processes, it adds up.

A rough picture: if an application imports 300 modules and compiling them without a cache costs 0.5 s in total, then every cold start pays half a second. With the cache present, it pays almost none of it. That is why container builds for short-lived workloads pre-compile with python -m compileall.

It never speeds up the loop you wrote.

"What happens on a read-only filesystem?"

Python tries to write the __pycache__ file, fails, and carries on without complaint. Your program still works. The cost is that nothing is cached, so every start compiles every imported module again. Start-up gets slower, sometimes by a lot, for large applications.

Two fixes:

  1. Pre-compile at build time: run python -m compileall in the image build step, before the filesystem becomes read-only. The .pyc files are then already there and are reused.
  2. Redirect the cache: set PYTHONPYCACHEPREFIX to a writable directory, such as /tmp/pycache. Python then stores the cache files there instead of next to the sources.

The second variable has a bonus. It keeps __pycache__ folders out of your source tree altogether, which is tidy in development. Remember that a path under /tmp is lost when the container restarts, so for repeated starts the build-time option is better.

"How do reproducible builds use hash-based pycs?"

A normal timestamp-based .pyc header contains the source file's modification time. The same source built on two machines, or on two days, therefore produces different .pyc bytes, and the image changes even though nothing in the code did. That breaks bit-for-bit reproducible builds and defeats layer caching.

Hash-based files (PEP 552) put a hash of the source in the header instead. The output depends only on the source and the Python version. There are two modes:

  1. Checked: at import, Python re-hashes the source and compares. It is safe if the source changes, at a small cost.
  2. Unchecked: Python trusts the file and does not even look at the source. It is the fastest and the most reproducible, and it is correct only if the source can never change after the build, as in a sealed image.

You create them with python -m compileall --invalidation-mode checked-hash (or unchecked-hash). The environment variable SOURCE_DATE_EPOCH gives a similar effect for timestamp-based builds, by fixing the recorded time.

Q65. "Why doesn't Python do tail-call optimisation, and what is the recursion limit protecting?"

Reveal answer

Strong answer Tail-call optimisation would reuse the current frame for a call in tail position, so deep recursion costs no stack. CPython does not do it, mainly by design: Guido van Rossum wanted tracebacks to stay complete. With TCO the frames of earlier calls vanish, and a traceback no longer shows how you got there. He also argued that loops are the Pythonic way to iterate.

So each recursive call creates a new frame, and the recursion limit (default 1,000, sys.getrecursionlimit()) stops runaway recursion from using memory without bound or, in older versions, from crashing the process by overflowing the C stack. Exceeding it raises RecursionError, which you can catch.

Since 3.11, pure-Python calls no longer consume C stack, so the limit is more about frame memory and sanity than about crashes, but it still exists, and calls through C code (such as map with a Python callback, or __getattr__) are protected separately.

Practical answer: convert deep recursion to a loop with an explicit stack or use iteration, rather than raising the limit. Raising it is a smell, and in older versions could crash.

Picture it The limit, the depth reached, a recursion that fails and the loop that fixes it.

The setup: Measure how deep a function gets, then compute a factorial both ways.

q65_recursion.py · Python 3.14runs offline
import sys

print("recursion limit:", sys.getrecursionlimit())

def depth(n=0):
    try:
        return depth(n + 1)
    except RecursionError:
        return n
print("deepest call reached:", depth())

def fact_rec(n):
    return 1 if n <= 1 else n * fact_rec(n - 1)

def fact_loop(n):
    result = 1
    for k in range(2, n + 1):
        result *= k
    return result

try:
    fact_rec(5000)
except RecursionError as e:
    print("fact_rec(5000) ->", type(e).__name__ + ":", e)
print("fact_loop(5000) has", fact_loop(5000).bit_length(), "bits")

try:
    fact_rec(5000)
except RecursionError:
    import traceback
    lines = traceback.format_exc().splitlines()
    print("traceback lines:", len(lines), "| it folds repeats:", [l for l in lines if "repeated" in l])
output · Python 3.14runs offline
recursion limit: 1000
deepest call reached: 998
fact_rec(5000) -> RecursionError: maximum recursion depth exceeded
fact_loop(5000) has 54233 bits
traceback lines: 15 | it folds repeats: ['  [Previous line repeated 996 more times]']

What you see: the limit is 1,000 and the measured depth is just under it; the recursive factorial fails at 5,000 while the loop handles it; and the traceback prints a single "Previous line repeated" line instead of a thousand frames.

Why: every call needs a frame; the limit caps how many exist at once.

Java · Spring

StackOverflowError at the stack size.

Deep.javaruns offline
int f(int n) { return f(n+1); }
// StackOverflowError after
// ~10,000-20,000 frames (JVM
// default stack, -Xss tunes)

Python

RecursionError at the limit.

deep.pyruns offline
def f(n): return f(n + 1)
# RecursionError at ~1,000
# (sys.setrecursionlimit)

The shift: Neither language removes tail calls, but Python stops at a small configured count, while the JVM stops when its thread stack is full.

Land it I say CPython keeps every frame to preserve full tracebacks, the limit of 1,000 stops runaway recursion, and I turn deep recursion into loops or explicit stacks instead of raising the limit.

Likely follow-ups
"Can I raise the limit safely?"

Safely, only up to a point, and I treat it as a last resort. sys.setrecursionlimit(10_000) simply moves the guard. It works until the real resource runs out, which is memory for frames, or the C stack when the recursion goes through C code.

The dangerous case is threads. Each thread has its own stack, usually smaller than the main thread's, and its size is fixed when the thread starts. If your limit is higher than what the stack can hold, the process can crash with a segmentation fault before Python raises RecursionError. A crash is far worse than an exception, because you cannot catch it.

Frames also cost memory. A hundred thousand live frames is not a small allocation, and the traceback is long if it fails.

So I raise it only for a known, bounded case, such as parsing a deeply nested but finite document that I control, and I set it just above the proven depth. If depth can grow with the input, I write an iterative version instead.

"What are the right ways to avoid deep recursion?"

The general idea is to replace the call stack with a data structure you control.

  1. Explicit stack: for trees and graphs, keep a list of nodes still to visit: stack = [root], then while stack: node = stack.pop(), and push the children. Depth is limited by memory, not by the recursion limit.
  2. Loops for linear definitions: a factorial or a sum over a chain is a for loop.
  3. Folds: functools.reduce or itertools.accumulate replace recursion that combines items one by one.
  4. Memoise overlapping subproblems: lru_cache avoids repeated work, but remember that a cached recursive function still recurses deeply on its first call.

There is a security angle too. If you traverse data you do not control, such as JSON from users, recursive code can be crashed with a deeply nested input. An iterative traversal removes that denial-of-service risk, so it is better in code facing the network.

"Does the JSON module or pickle have recursion issues?"

Yes. A deeply nested input makes the parser recurse, and past the limit it raises RecursionError. The standard json module in pure-Python mode, and pickle, both behave this way, and C implementations have their own depth guards.

That is a protection, not a bug. Imagine an attacker who sends [[[[ ... ]]]] with 100,000 levels of nesting. Without a guard, the parser would recurse until it ran out of stack and could crash the process. With the guard, you get an exception that you can catch and turn into a clean 400 response.

The right defence is at the edge of the system. Limit the request size and, where it makes sense, the nesting depth, and reject anything beyond it before parsing deeply. Raising the recursion limit to accept the hostile input is exactly the wrong response.

Also never pickle.loads data from an untrusted source: its danger is code execution, which is a bigger issue than recursion.

"Is there any tail-call work in recent Python?"

There is something with a similar name, and it is easy to confuse with it. Python 3.14 added an optional build mode, the tail-calling interpreter. It uses the compiler's musttail support (in recent Clang versions) so the interpreter's own instruction handlers jump to each other instead of going through one big switch. That makes the interpreter loop itself faster, on builds that enable it. It is a build option, not a language feature.

It has nothing to do with your recursive functions. Each Python-level call still creates a frame, and the recursion limit still applies. A function like def f(n): return f(n - 1) is not optimised.

So keep the two ideas apart in an interview. One is faster dispatch inside the virtual machine. The other is eliminating frames in the user program, and CPython still deliberately does not do that, to keep tracebacks complete.

Q66. "What is the experimental JIT (3.13+), and should you turn it on?"

Reveal answer

Strong answer A JIT (just-in-time compiler) translates frequently run code into machine code while the program runs. CPython 3.13 added an experimental copy-and-patch JIT (PEP 744). It is built from small pre-compiled machine-code templates for each micro-operation of the specialised interpreter; at run time it copies the right templates together and patches in the addresses and constants. That makes the compiler small and fast to start, but also limits how much it can optimise.

It is off by default. It exists only in builds configured with it, and is switched on with the environment variable PYTHON_JIT=1. It only works on code that the specialising interpreter (Q63) has already made hot, and first gains were small. Python 3.15 reports a geometric-mean improvement of about 7 to 8 percent on x86-64 Linux in the project's benchmarks; I would quote it as "reported" and not as a promise for your workload.

Should you turn it on? Not blindly. Measure your real workload with and without it. Possible downsides: extra memory for generated code, longer warm-up, and the fact that it is still labelled experimental. Possible gains: tight pure-Python loops. If your time goes to I/O, the database or C extensions, expect nothing. The decision rule is "measure, don't assume".

Picture it Is the JIT in this build, and what does it do to a numeric loop on 3.14 and 3.15?

The setup: Check sys._jit, then run the same loop in child interpreters with PYTHON_JIT unset and set to 1.

q66_jit_measure.py · Python 3.14runs offline
import os, subprocess, sys, textwrap

HERE = sys.executable
U = "/home/iam100god/.local/share/uv/python/"
INTERPRETERS = {"3.14": U + "cpython-3.14.7-linux-x86_64-gnu/bin/python3.14",
                "3.15.0rc1": U + "cpython-3.15-linux-x86_64-gnu/bin/python3.15"}

child = textwrap.dedent("""
    import sys, time
    def work(n):
        total = 0
        for i in range(n):
            total += (i * 3) % 7
        return total
    work(200_000)                                  # warm up
    best = min(__import__("timeit").repeat(lambda: work(2_000_000), number=1, repeat=5))
    print(f"{best:.3f}", sys._jit.is_enabled(), sys._jit.is_active())
""")

print("JIT available in this build:", sys._jit.is_available())
for name, exe in INTERPRETERS.items():
    for env_value in (None, "1"):
        env = {k: v for k, v in os.environ.items() if k != "PYTHON_JIT"}
        if env_value:
            env["PYTHON_JIT"] = env_value
        out = subprocess.run([exe, "-c", child], capture_output=True, text=True, env=env).stdout.split()
        label = "PYTHON_JIT=1" if env_value else "default     "
        print(f"Python {name:10} {label}: best of 5 = {out[0]} s  (enabled={out[1]}, active={out[2]})")
output · Python 3.14runs offline
JIT available in this build: True
Python 3.14       default     : best of 5 = 0.081 s  (enabled=False, active=False)
Python 3.14       PYTHON_JIT=1: best of 5 = 0.097 s  (enabled=True, active=False)
Python 3.15.0rc1  default     : best of 5 = 0.094 s  (enabled=False, active=False)
Python 3.15.0rc1  PYTHON_JIT=1: best of 5 = 0.072 s  (enabled=True, active=False)
# measured on the course machine; your numbers will differ; small effect, noisy

What you see: enabled=True confirms the switch took effect. In this run the JIT made 3.14 slower (0.081 s to 0.097 s) and 3.15 faster (0.094 s to 0.072 s). Differences this small and this inconsistent between versions show why the rule is to measure your own workload, repeatedly, before trusting any JIT claim.

Why: the JIT works only on already-specialised hot traces, so it is an incremental speed-up on top of the interpreter, not a different execution model.

Java · Spring

JIT is the default engine.

Hot.txtruns offline
HotSpot: interpret, profile,
compile hot code with C1/C2
always on, tuned by flags

Python

JIT is an opt-in extra.

py.txtruns offline
PYTHON_JIT=1 python app.py
small templates, small gains,
off by default, experimental

The shift: Java was designed around its JIT; CPython's is a young, optional add-on that gains a few percent so far.

Land it I say the JIT is an experimental, off-by-default copy-and-patch compiler enabled with PYTHON_JIT=1, gains are modest and reported at a few percent, and I would adopt it only after measuring my own workload.

Likely follow-ups
"Why copy-and-patch rather than a classic optimising JIT?"

Because it is much cheaper to build and maintain, and it starts fast. In copy-and-patch, the compiler toolchain (LLVM) produces a small machine-code template for each micro-operation of the interpreter at CPython build time. At run time the JIT only copies the needed templates into a buffer, in order, and patches in the concrete addresses and constants. There is no heavy analysis in the running program.

A classic optimising JIT, such as HotSpot's C2 or PyPy's tracing JIT, does a great deal at run time: it profiles, builds an intermediate form, optimises and generates code. That is a very large engineering project, it needs a lot of memory and warm-up time, and it is hard to keep correct against a language as dynamic as Python.

The trade-off is peak speed. Copy-and-patch gives code that is only modestly faster than the interpreter, because the templates are fixed. The plan is to add optimisations on top over several releases, using the same foundation. For now the honest summary is small, steady gains with low risk of slow starts.

"How is PyPy different?"

PyPy is a separate implementation of Python, not a mode of CPython. It has a tracing JIT that records hot loops and compiles them with real optimisations. On pure-Python, CPU-bound code, such as loops and numeric work, it is often several times faster than CPython.

The costs matter when choosing it:

  1. Extensions: libraries written against CPython's C API run through an emulation layer or not at all. NumPy works, but some packages do not.
  2. Memory and warm-up: it uses more memory and is slow for the first moments of a short program.
  3. Versions: its release schedule lags behind CPython, so the newest language features arrive later.

My decision rule: for a pure-Python, CPU-bound service with ordinary dependencies, benchmark PyPy on real data before ruling it out. For a service built on a heavy extension ecosystem, such as machine-learning libraries or database drivers with native parts, stay on CPython and look at the experimental JIT, vectorising or moving the hot loop to native code.

"Would the JIT help a web service?"

Probably not by much. Look at where a typical request spends its time: waiting on a database or another service, in JSON encoding that is already done in C, in the HTTP server, and in framework code that touches many different types. None of that is the kind of code the JIT helps.

The JIT likes tight, repetitive, type-stable loops in pure Python. A request handler is mostly I/O and glue, with a different shape on each call, which specialisation itself already handles about as well as it can. If a request takes 50 ms and 45 ms of it is waiting for the database, even a doubling of Python speed changes the response time by only a few milliseconds.

So I would profile first (Q104) and find where the time goes. If one hot loop dominates, vectorise it or move it to native code, which gives far larger and more certain gains. If most time is waiting, fix queries, caching or concurrency instead. I would treat the JIT as the last and smallest lever.

"Is it safe to enable in production?"

Treat it as an experiment you control, not as a default. The release notes call it experimental, which means its performance, memory use and even its availability can change between versions, and the project does not promise production stability.

  1. Canary: turn it on for a small slice of instances, with the same traffic as the rest.
  2. Compare: look at latency percentiles (p50 and p99), CPU, and memory against the control group over a long enough window, such as a full daily cycle.
  3. Keep the exit easy: it is controlled by an environment variable (PYTHON_JIT=1), so turning it off is a restart, with no rebuild.

Prefer to change one thing at a time, so that a regression has one possible cause. I would also confirm that the interpreter in my image was built with JIT support at all, since a default build ignores the switch.

Re-read the notes for your exact version before deciding, because its maturity is moving quickly.

Q67. "How are exceptions "zero-cost" since 3.11?"

Reveal answer

Strong answer Before 3.11, entering a try block executed a SETUP_FINALLY instruction that pushed a handler onto a block stack, so even code that never raised paid a small cost for each try. Since 3.11, a try compiles to no instruction at all on the normal path. The compiler stores a separate exception table next to the bytecode, listing "if an exception happens between these instruction offsets, jump to this handler".

When nothing is raised, nothing consults the table, so the cost of try is zero. When something is raised, the interpreter looks up the table, which costs more than the old scheme: the cost moved from the happy path to the failure path.

Consequences. The EAFP style ("easier to ask forgiveness than permission", try: value = d[key] except KeyError:) is cheap when the key usually exists and expensive when it usually does not. Raising and catching an exception is still much slower than an if test (about 130 nanoseconds against about 20 here), because an exception object and a traceback must be built. "Zero-cost" refers to setting up the try, not to raising.

Picture it The exception table in dis, and the timing of try with and without raising.

The setup: A function with a try/except; dis shows the table, and timeit compares three variants.

q67_zero_cost_try.py · Python 3.14runs offline
import dis, timeit

def guarded(d, k):
    try:
        return d[k]
    except KeyError:
        return None

dis.dis(guarded)
print()

d = {"a": 1}
n = 2_000_000
t_try_ok = timeit.timeit("try:\n    d['a']\nexcept KeyError:\n    pass", globals={"d": d}, number=n)
t_plain = timeit.timeit("d['a']", globals={"d": d}, number=n)
t_try_raise = timeit.timeit("try:\n    d['zz']\nexcept KeyError:\n    pass", globals={"d": d}, number=n)
t_get = timeit.timeit("d.get('zz')", globals={"d": d}, number=n)
print(f"plain d['a']                  : {t_plain / n * 1e9:7.1f} ns")
print(f"try around d['a'] (no raise)  : {t_try_ok / n * 1e9:7.1f} ns   <- try itself costs ~nothing")
print(f"try around d['zz'] (raises)   : {t_try_raise / n * 1e9:7.1f} ns   <- raising is expensive")
print(f"d.get('zz') (no exception)    : {t_get / n * 1e9:7.1f} ns")
output · Python 3.14runs offline
   3           RESUME                   0

   4           NOP

   5   L1:     LOAD_FAST_BORROW_LOAD_FAST_BORROW 1 (d, k)
               BINARY_OP               26 ([])
       L2:     RETURN_VALUE

  --   L3:     PUSH_EXC_INFO

   6           LOAD_GLOBAL              0 (KeyError)
               CHECK_EXC_MATCH
               POP_JUMP_IF_FALSE        5 (to L5)
               NOT_TAKEN
               POP_TOP

   7   L4:     POP_EXCEPT
               LOAD_CONST               0 (None)
               RETURN_VALUE

   6   L5:     RERAISE                  0

  --   L6:     COPY                     3
               POP_EXCEPT
               RERAISE                  1
ExceptionTable:
  L1 to L2 -> L3 [0]
  L3 to L4 -> L6 [1] lasti
  L5 to L6 -> L6 [1] lasti

plain d['a']                  :    16.8 ns
try around d['a'] (no raise)  :    17.7 ns   <- try itself costs ~nothing
try around d['zz'] (raises)   :   129.5 ns   <- raising is expensive
d.get('zz') (no exception)    :    23.1 ns
# measured on the course machine; your numbers will differ

What you see: the listing ends with an ExceptionTable mapping an instruction range to the handler, and there is no setup instruction at the top of the try. The try around a successful lookup costs about the same as the lookup alone; the lookup that raises costs many times more.

Why: the handler list lives beside the code, and is read only when an exception is actually raised.

Java · Spring

Exception table too.

Jvm.txtruns offline
JVM also uses an exception
table per method: no cost
on the normal path; throw
is slow (stack trace fill)

Python

Same idea since 3.11.

py.txtruns offline
try: no instruction emitted
raise: look up table, build
exception + traceback
(~100+ ns)

The shift: Both runtimes make try free and throw expensive; Python reached the JVM's design in 3.11.

Land it I say try compiles to an exception table with no instructions on the normal path, so it is free when nothing is raised, but raising is still slow, so I do not use exceptions for control flow that fires often.

Likely follow-ups
"So is EAFP always fine?"

When failure is rare, yes. The happy path pays nothing, the code is shorter, and it says what you mean. That is the situation it was designed for, such as a key that nearly always exists.

When failure is common, no. Take a cache that misses half the time. Each miss builds an exception object and a traceback, which is around 130 ns here against about 23 ns for d.get(key). At ten million lookups with a 50 percent miss rate, the exceptions alone add more than half a second. In that case use if key in d or d.get(key).

There is also a correctness reason to prefer EAFP ("easier to ask forgiveness than permission") in concurrent code. If you check first and act afterwards, the world can change between the two steps: the file you saw is gone when you open it. Trying the action and handling the failure has no such gap.

My rule: pick by how often the failure happens, and by whether check-then-act can race.

"What happened to finally and with?"

They use the same exception table, and the design keeps the normal path straight. A try/finally or a with block has cleanup code that must run on two paths: when the body finishes normally, and when an exception passes through. The compiler writes the cleanup once inline for the normal path, and again as a separate "cold" copy that the exception table points at.

That duplication explains something that surprises people. If you disassemble a function with a finally, the bytecode looks longer than the source suggests, because the cleanup appears twice (or more, with several exits). It is not a sign of waste. The extra copy is never executed unless something goes wrong.

The same holds for with: the call to __exit__ is placed on the normal path and again in a handler. The take-away for design is that cleanup code costs nothing extra when nothing fails, so you should use with and finally freely and not avoid them for speed.

"What does a raise cost, in practice?"

On the course machine, one raise and catch of a KeyError cost about 130 ns, while dict.get cost about 23 ns. Here is what that means as arithmetic:

raise costruns offline
10,000,000 raises x 130 ns = 1,300 ms = 1.3 s
10,000,000 gets   x  23 ns =   230 ms = 0.23 s
difference                 = about 1.1 s

So a loop of ten million items that raises on every one spends over a second just on exceptions. The cost grows with stack depth, since the traceback gets one entry for each frame the exception passes through.

There is one special case: the StopIteration that ends a for loop is handled in C without building a full Python exception, which is why iteration itself stays fast.

I do not worry about 130 ns for a rare event. I do worry when it is the usual path of a hot loop.

"Does try affect other optimisations?"

Not in a way that matters to you. The specialising interpreter treats the code inside a try block like any other code, so loads, arithmetic and calls are specialised in the normal way. There is no penalty for being in a try.

In older versions, before the exception table, the block stack made some control flow awkward and cost a small amount on entry. That is part of why 3.11 got faster overall, along with the specialiser.

The useful rule is therefore about clarity, not speed. Keep the code inside the try as narrow as possible: only the one call that can raise the exception you handle. A wide try can catch an error from an unrelated line and hide a bug, and it makes it harder to see what the handler is for.

Likewise catch the specific exception, such as KeyError, and not a bare except or except Exception unless you re-raise or log.

Q68 · Scenario. "A hot loop does obj.a.b.c lookups ten million times. How do you measure it and make it faster?"

Reveal answer

Strong answer Measure first, in this order. 1. Is this loop really the hot spot? Profile the program (cProfile, Q104); if the loop is 2 % of the time, stop. 2. Isolate it in a function and time it with timeit or time.perf_counter, best of several runs, on realistic data, on the Python version you deploy. 3. Look at the cost per iteration in nanoseconds, to know what a gain is worth.

Then the options, cheapest first. Hoist invariant lookups out of the loop: c = obj.a.b.c once, or get = obj.a.b.get for a method. A local variable read is the fastest lookup Python has. Reduce the number of dots by flattening the data structure or caching the inner object. Use __slots__ if obj is an instance with many attributes (small gain, Q110). Vectorise or batch the loop (sum(map(...)), NumPy, Q108). Native code (Cython, numba, Rust) if the loop is the whole program.

Know why it helps: each . is a lookup that, even specialised, costs a few nanoseconds; a local is one array read. Since 3.11 the specialising interpreter caches attribute lookups, so the gain from hoisting is smaller than it used to be, which is exactly why you measure rather than recall folklore.

Picture it Ten million lookups, chained versus hoisted, with the real timings.

The setup: A three-level object chain; the loop reads obj.a.b.c each time, or reads c once into a local.

q68_attribute_chain.py · Python 3.14runs offline
import timeit

class C:
    def __init__(self):
        self.value = 3
class B:
    def __init__(self):
        self.c = C()
class A:
    def __init__(self):
        self.b = B()
class Obj:
    def __init__(self):
        self.a = A()

obj = Obj()
N = 10_000_000

def chained():
    total = 0
    for _ in range(N):
        total += obj.a.b.c.value
    return total

def hoisted():
    value_holder = obj.a.b.c
    total = 0
    for _ in range(N):
        total += value_holder.value
    return total

def local_only():
    v = obj.a.b.c.value
    total = 0
    for _ in range(N):
        total += v
    return total

for fn in (chained, hoisted, local_only):
    best = min(timeit.repeat(fn, number=1, repeat=3))
    print(f"{fn.__name__:11}: {best:5.2f} s  = {best / N * 1e9:5.1f} ns per iteration")
output · Python 3.14runs offline
chained    :  0.35 s  =  34.7 ns per iteration
hoisted    :  0.22 s  =  22.1 ns per iteration
local_only :  0.19 s  =  19.4 ns per iteration
# measured on the course machine; your numbers will differ

What you see: the chained version is slowest, the hoisted version removes three lookups per iteration and gains a measurable amount, and the local-only loop shows the floor: the cost of the loop and the addition alone.

Why: every dot is a dictionary or slot lookup behind a cache; a local variable is a direct array read.

Chained

Look up each time.

chain.pyruns offline
for _ in range(N):
    total += obj.a.b.c.value

Hoisted

Look up once.

hoist.pyruns offline
c = obj.a.b.c
for _ in range(N):
    total += c.value

The shift: Pull anything that does not change out of the loop; the gain is the lookups you stop repeating.

Land it I profile to confirm the loop matters, time it in isolation with timeit, hoist invariant lookups into locals, and only then consider vectorising or native code, quoting nanoseconds per iteration.

Likely follow-ups
"How do I get a trustworthy timing?"

Use timeit.repeat and take the minimum, not the average. Noise from other processes, the operating system and frequency scaling can only add time to a run, never remove it, so the fastest run is the closest to the true cost.

  1. Warm up: run the code once first, so that the specialiser has settled and caches are warm.
  2. Same conditions: use the Python version you deploy, an idle machine, and data of production size.
  3. Repeat: five to ten runs, and report the minimum with the spread.
  4. Compare in one process: run both variants in the same script, alternating, so a background load hits both equally.

Then watch out for measuring the wrong thing. A constant expression can be folded away by the compiler. A tiny input can fit in the CPU cache and give numbers that a larger input never repeats. And a loop whose result is never used may be easy for you to write but tells you little.

Finally convert to a unit that has meaning: nanoseconds per iteration, so you know what a saving is worth.

"Is the hoisting still worth it after 3.11?"

Often it is worth measuring each time. Before 3.11, obj.a.b.c meant three full attribute lookups with dictionary searches. Since 3.11 the specialiser caches where each attribute lives, so a repeated lookup on the same type of object is cheaper, and the gain from hoisting it into a local is smaller.

The other half of the answer is the size of the loop body. If each iteration also calls a function, formats a string or does a dictionary update, the lookups were a small part of the cost, and removing them is invisible. Hoisting pays when the profile points at this loop and the body is tiny, such as a sum of one attribute over millions of items.

It is still cheap to try, since the change is one line and a local variable also reads well. So I would hoist when the loop is proven hot, measure on my version, keep it if it helps, and revert it if it does not.

I would not rewrite working code on folklore from older versions.

"What about dict access versus attributes?"

They are close in cost, so I would not reshape data for the sake of speed. A dictionary key lookup is fast but not free: it hashes the key and probes a table. An attribute access on an ordinary instance also does a dictionary lookup in the background, helped by caches. Slotted attributes are a little cheaper, since they sit at a fixed offset, and the memory saving is bigger than the speed gain.

The same goes for a tuple index. row[3] can be a few nanoseconds faster than row.price. But the readability loss is serious: nobody remembers what index 3 means in six months. A NamedTuple or a dataclass with slots=True keeps the names and costs almost nothing extra.

My order of concern is clarity first, then the algorithm and the number of lookups, then micro-details. Replacing obj.a.b.c with tuple indices is rarely worth the loss. If a profile ever shows this is the bottleneck, I would compare three or four layouts in a benchmark and then choose.

"When is it time for numpy or Cython?"

When the loop body is plain arithmetic over many items, a profile shows that this loop dominates the run time, and the work can be expressed on whole arrays. Then NumPy is the first choice: the loop moves into compiled C code that works on raw numbers.

  1. Vectorise with NumPy: replace the Python loop with array operations (Q108). For arithmetic, speed-ups of tens of times are common.
  2. Compile with numba or Cython: when the logic is irregular, with branches and early exits, that does not map to array operations. You add type information, and the loop becomes machine code.
  3. Rewrite in Rust or C: when the loop is the whole program, or you need it as a reusable library (Q109).

Before choosing, write the target in numbers, such as "from 4 s to 0.2 s per batch", so that you know when you are done and whether the extra build complexity paid off.

If the profile shows many small costs spread around, none of these will help, and the right move is to leave the code alone.

Q69. "What are t-strings (3.14), and what problem do they solve that f-strings cannot?"

Reveal answer

Strong answer A t-string (template string, PEP 750, Python 3.14) looks like an f-string with a t prefix: t"SELECT * FROM users WHERE id = {user_id}". But it does not produce a str. It produces a string.templatelib.Template object that keeps the literal text parts and the interpolated values separate, so code can inspect and process them before building any final string.

An f-string merges everything into one string at once. Once merged, the program cannot tell which characters were your literal text and which came from a user. That is the root of injection bugs: SQL injection, HTML injection (XSS), shell injection, log injection. With a t-string, a function receives the pieces and can escape or parameterise each value properly: values become ? placeholders for a SQL driver, or get HTML-escaped, or are quoted for a shell.

So t-strings do not make anything safe by themselves. They give libraries a safe hook: a function sql(template) that returns a query and parameter list. The caller writes natural-looking code, and the library does the right thing. Use them wherever you would be tempted to build a query, HTML or command by f-string.

Picture it What a Template contains, and a helper that turns it into a parameterised query.

The setup: A t-string with a hostile value; compare an f-string, then process the Template into a query with ? placeholders.

q69_tstrings.py · Python 3.14runs offline
from string.templatelib import Template, Interpolation

user_input = "x'; DROP TABLE users; --"

unsafe = f"SELECT * FROM users WHERE name = '{user_input}'"       # ❌ TRAP: one merged string
print("f-string :", unsafe)

tmpl = t"SELECT * FROM users WHERE name = {user_input}"
print("type     :", type(tmpl).__name__)
print("strings  :", tmpl.strings)
print("values   :", tmpl.values)
print("parts    :", [p if isinstance(p, str) else f"<{p.expression}={p.value!r}>" for p in tmpl])

def to_sql(template: Template):
    query, params = [], []
    for part in template:
        if isinstance(part, Interpolation):
            query.append("?")                                       # value never enters the SQL text
            params.append(part.value)
        else:
            query.append(part)
    return "".join(query), params

print("safe     :", to_sql(tmpl))

def to_html(template: Template):
    import html
    return "".join(html.escape(str(p.value)) if isinstance(p, Interpolation) else p for p in template)

page = t"<p>Hello {'<script>alert(1)</script>'}</p>"
out = to_html(page)
print("html     : <script> still present?", "<script>" in out, "| ampersand escapes inserted:", out.count("&"))
output · Python 3.14runs offline
f-string : SELECT * FROM users WHERE name = 'x'; DROP TABLE users; --'
type     : Template
strings  : ('SELECT * FROM users WHERE name = ', '')
values   : ("x'; DROP TABLE users; --",)
parts    : ['SELECT * FROM users WHERE name = ', '<user_input="x\'; DROP TABLE users; --">']
safe     : ('SELECT * FROM users WHERE name = ?', ["x'; DROP TABLE users; --"])
html     : <script> still present? False | ampersand escapes inserted: 4

What you see: the f-string embeds the attack into the SQL text, while the Template keeps strings and values apart, so to_sql emits ? and a parameter list, and to_html escapes the script tag.

Why: the template defers joining; the processing function decides how each value is turned into text.

f-string

Merges, then it is too late.

f.pyruns offline
q = f"... WHERE n = '{name}'"
db.execute(q)
# injection possible

t-string

Keeps parts separate.

t.pyruns offline
q = t"... WHERE n = {name}"
db.execute(q)   # driver binds ?
# value never joins the text

The shift: An f-string is a finished string; a t-string is a recipe that a library can execute safely.

Land it I describe a t-string as a Template that keeps literal parts and values separate, so a library can parameterise SQL or escape HTML, which an already-merged f-string cannot do.

Likely follow-ups
"Do t-strings stop SQL injection by themselves?"

No. A t"..." literal gives you a Template object, not a string, and by itself that makes nothing safe. It is a better starting point, not a defence.

One small protection comes for free. If you pass a Template where a str is expected, such as to cursor.execute in a driver that has not added support, it fails loudly with a type error instead of quietly concatenating the data. That prevents the worst habit.

The real safety comes from the code that consumes the template. A helper or a driver that accepts a Template sees the fixed text and the values separately. It can turn each value into a ? placeholder, collect the values into a parameter list, and pass them to the database as data. Until your database library does that, wrap it with a small function such as the to_sql helper shown in the chapter.

The underlying defence is still the parameterised query. T-strings make writing one as natural as writing an f-string, which removes the temptation to cheat.

"What about formatting specs like {price:.2f}?"

Each {...} in a t-string becomes an Interpolation object that carries four pieces of information. The template does not apply any of them. The code that consumes the template chooses what to do.

  1. value: the evaluated result, for example the number 19.5.
  2. expression: the source text inside the braces, such as "price".
  3. conversion: !r, !s or !a, or none.
  4. format_spec: the text after the colon, such as ".2f".

So {price:.2f} does not format anything by itself. A helper that builds display text can apply the format spec with format(value, format_spec). A helper that builds SQL ignores the spec and binds the raw value, which is what you want for a database.

The expression field is a pleasant extra for structured logging. From t"user {user_id}", a logger can record the key user_id with its value 42, with no separate keyword arguments.

"How do they compare with string.Template and %?"

They solve a different problem. string.Template is the older tool: it has $name placeholders, looks the names up in a dictionary at the moment you call substitute, and does not allow expressions. Because the text is data, it can come from a user or a file. The % operator is the oldest style, and works on positional or named values.

A t-string is written in your code, like an f-string, and its expressions are evaluated right there, where it is written. The only thing that differs from an f-string is that joining the pieces into one string is deferred, so a function can process the parts first.

So the three have different jobs:

  1. f-string: format now, in code you write.
  2. t-string: keep the pieces, in code you write, and let a function decide how to join them safely.
  3. string.Template: fill a template text that was given to you at run time.

Never eval or exec text from users to emulate a t-string.

"Where will I meet them?"

In libraries that choose to adopt PEP 750, and that will take time. The natural places are SQL helpers that turn a template into a query and a parameter list, HTML templating that escapes each value, shell-command builders that quote arguments, and structured logging that records both message and values.

The standard library gives you the building blocks: the Template and Interpolation types in string.templatelib. It does not ship a general-purpose renderer. So either a library supplies the function that consumes templates, or you write a small one yourself, which is typically ten to twenty lines for SQL.

That is the honest status. The feature is new in Python 3.14, library support is still arriving, and many databases and web frameworks do not yet accept a Template directly. In an interview I would say what it enables, show the small helper, and add that I would check each library's documentation before relying on it. That last remark shows the senior habit of verifying instead of assuming.

Q70. "Which changes from 3.11 to 3.15 should a senior Python engineer be able to explain?"

Reveal answer

Strong answer Group them by what they change for you. Speed: 3.11 specialising interpreter (about 25 percent faster on average), zero-cost try (Q67); 3.13 experimental JIT, 3.14 and 3.15 improvements to it (Q66). Concurrency: 3.11 asyncio.TaskGroup, asyncio.timeout and exception groups with except*; 3.12 per-interpreter GIL at the C level; 3.13 experimental and 3.14 officially supported free-threaded build (PEP 703, PEP 779); 3.14 concurrent.interpreters and InterpreterPoolExecutor (PEP 734); 3.14 default multiprocessing start method forkserver on Linux.

Language and typing: 3.12 type statements and def first[T](...) generics (PEP 695), more flexible f-strings (PEP 701); 3.14 deferred evaluation of annotations (PEP 649) and t-strings (PEP 750); 3.15 explicit lazy import (PEP 810) and the frozendict built-in (PEP 814). Operations: 3.11 tomllib; 3.14 compression.zstd, asyncio introspection (python -m asyncio ps); 3.15 the profiling package with the Tachyon sampling profiler (attach to a running process) and UTF-8 mode on by default (PEP 686).

In an interview I would not recite the list. I would pick three that matter for the job, say what problem each solves, and say what I measured or checked. Anything from 3.14 and 3.15 should be confirmed against the official What's New page before relying on details.

Picture it A feature probe run in four interpreters, so the table is evidence and not memory.

The setup: One script asks each local interpreter what it supports.

q70_version_probe.py · Python 3.12runs offline
import subprocess

U = "/home/iam100god/.local/share/uv/python/"
INTERPRETERS = {
    "3.12": "/home/iam100god/Desktop/AI_COURSE/.venv/bin/python",
    "3.14": U + "cpython-3.14.7-linux-x86_64-gnu/bin/python3.14",
    "3.14t": U + "cpython-3.14.7+freethreaded-linux-x86_64-gnu/bin/python3.14t",
    "3.15": U + "cpython-3.15-linux-x86_64-gnu/bin/python3.15",
}

probe = r'''
import sys, multiprocessing, itertools, asyncio
def compiles(src):
    try:
        compile(src, "<probe>", "exec"); return "yes"
    except SyntaxError:
        return "no"
def has_module(name):
    try:
        __import__(name); return True
    except ImportError:
        return False
gil = sys._is_gil_enabled() if hasattr(sys, "_is_gil_enabled") else "n/a"
checks = [
    ("version", sys.version.split()[0]),
    ("TaskGroup (3.11)", hasattr(asyncio, "TaskGroup")),
    ("type statement (3.12)", compiles("type X = int")),
    ("itertools.batched (3.12)", hasattr(itertools, "batched")),
    ("GIL enabled", gil),
    ("t-strings (3.14)", compiles('t"a{1}"')),
    ("concurrent.interpreters (3.14)", has_module("concurrent.interpreters")),
    ("compression.zstd (3.14)", has_module("compression.zstd")),
    ("lazy import (3.15)", compiles("lazy import json")),
    ("frozendict builtin (3.15)", "frozendict" in dir(__builtins__)),
    ("default mp start method", multiprocessing.get_start_method()),
]
for k, v in checks:
    print(k + "=" + str(v))
'''

results = {name: dict(line.split("=", 1) for line in subprocess.run([exe, "-c", probe], capture_output=True, text=True).stdout.splitlines())
           for name, exe in INTERPRETERS.items()}
keys = list(results["3.12"])
print(f"{'feature':32}" + "".join(f"{n:>12}" for n in results))
for k in keys:
    print(f"{k:32}" + "".join(f"{results[n][k]:>12}" for n in results))
output · Python 3.12runs offline
feature                                 3.12        3.14       3.14t        3.15
version                               3.12.3      3.14.7      3.14.7   3.15.0rc1
TaskGroup (3.11)                        True        True        True        True
type statement (3.12)                    yes         yes         yes         yes
itertools.batched (3.12)                True        True        True        True
GIL enabled                              n/a        True       False        True
t-strings (3.14)                          no         yes         yes         yes
concurrent.interpreters (3.14)         False        True        True        True
compression.zstd (3.14)                False        True        True        True
lazy import (3.15)                        no          no          no         yes
frozendict builtin (3.15)              False       False       False        True
default mp start method                 fork  forkserver  forkserver  forkserver

What you see: each column is a real interpreter. Features appear exactly where the version note says they do, the 3.14t column reports the GIL as disabled, and the default start method changes from fork to forkserver between 3.12 and 3.14.

Why: asking the interpreter is the fastest way to settle a "which version added it" question, and is the habit I want to show.

Land it I group the changes by effect (speed, concurrency, language and typing, operations), pick the three that matter for the job, and verify details against the What's New page and a probe run.

Likely follow-ups
"Which three would you pick for a web service team?"

Starting from the effect on the team, not from the release notes, I would choose three.

  1. 3.11 specialising interpreter: about 25 percent faster on average (reported, Q63), and it costs nothing but the upgrade itself. Every service benefits, so it pays for the upgrade effort by itself.
  2. 3.11 TaskGroup with except*: structured concurrency means that if one request task fails, the others are cancelled and the errors are reported together. Concurrent request handling becomes correct by construction, instead of relying on fire-and-forget tasks.
  3. Typing syntax and deferred annotations (3.12 to 3.14): def first[T](...), type aliases and lazy annotations remove friction and many forward-reference workarounds in typed code.

For a CPU-heavy team I would swap the last two for the free-threaded build and concurrent.interpreters, because parallel CPU work is what they lack. The principle in both cases is that I name the problem the feature solves and what I checked or measured, not just the version number.

"What breaks when upgrading?"

The breakage comes mostly from removals, stricter checks and changed defaults. From memory the notable ones are:

  1. Removed modules: distutils and asyncore went in 3.12, and old build scripts or libraries that import them stop working.
  2. Deprecations that turn into errors: datetime.utcnow() warns, and several old unittest aliases are gone.
  3. Dataclass checks: from 3.11, mutable defaults such as a list are refused more strictly (anything unhashable).
  4. Changed defaults: in 3.14 the multiprocessing start method on Linux moves from fork to forkserver, which breaks code that relied on inherited globals.

Verify the list for your versions in each "What's New" page, since details differ.

My method is to run the test suite one release early with -W error::DeprecationWarning, so deprecations fail in CI long before the removal. Then upgrade dependencies first, because a library without support for the new version is the most common blocker.

"Why does the default start method change matter?"

It matters because the two start methods give the child process a completely different starting state. With fork, the child is a copy of the parent at that moment: it inherits global variables, caches that were filled, open file handles and even locks that were held. With forkserver and spawn, the child is a fresh interpreter that imports your main module and receives only what you pass it.

Code that worked under fork by accident then fails in a few characteristic ways:

  1. Pickling errors: the target function and its arguments must be picklable, so lambdas and local functions fail.
  2. Main module runs again: an unguarded script re-executes its top level in each worker (Q73).
  3. Empty globals: a module-level cache filled in the parent is empty in the child.

The fix is to be explicit. Call multiprocessing.get_context("spawn") where the code must behave the same everywhere, pass needed data as arguments, and use the pool's initializer= to set up each worker.

"How do I decide when to adopt a new feature?"

I ask three questions, in this order, and I upgrade the interpreter before I adopt the features.

  1. Is the version supported? A Python release receives bug fixes for about two years and security fixes for five in total. If production is near the end of that window, the upgrade is a security task, not an option.
  2. Do the dependencies support it? Check that the libraries you rely on publish wheels for the new version. One missing wheel for a native library can block the whole move.
  3. Does the feature solve a problem I have? A new syntax is not a reason to rewrite working code.

Upgrading first and adopting later keeps the risk small: you get the automatic gains such as the faster interpreter, and you change the code in separate, reviewable steps.

For experimental features, such as the JIT and free-threading, I do not switch them on across the board. I run a controlled trial with a measurable goal and an easy way back (Q80).

Drill · Imports and the GIL

These questions test whether you know that import is executable and cached, how cycles and start-up cost arise, and what the GIL really protects, with measured numbers on the interpreters installed here.

Q71. "How does import x work — sys.modules, finders and loaders?"

Reveal answer

Strong answer import x is a runtime statement with a fixed algorithm. 1. Look in sys.modules, a dict of already-imported modules. If x is there, bind the name and stop: the module body does not run again. 2. If missing, ask the finders. The list sys.meta_path holds finder objects; each is asked "can you find x?".

The standard ones look at built-in modules, frozen modules, and the folders in sys.path (including zip files and site-packages). A finder that succeeds returns a spec: name, location, and which loader to use. 3. A loader creates the module object and executes its code in it. The module is put into sys.modules before its body runs (this is what makes circular imports possible, Q72). 4. The name is bound in the importing scope.

Facts that follow. A module's body runs once per process, so top-level code is a one-time initialiser, and a module is a natural singleton. import a.b imports a first, then a.b, and binds only the name a (you then write a.b.func).

from a import b binds b directly. Deleting from sys.modules forces a fresh import, which tests sometimes do and production code should not. Because finders are a list you can extend, tools install their own (import hooks for encrypted code, test frameworks that rewrite assertions, importlib.metadata entry points).

Picture it A package imported twice, what is cached, who found it, and what a forced re-import does.

The setup: A temporary package pkg with a submodule; each module prints when its body runs.

q71_import_system.py · Python 3.14runs offline
import importlib.util, os, sys, tempfile

with tempfile.TemporaryDirectory() as d:
    os.makedirs(os.path.join(d, "pkg"))
    open(os.path.join(d, "pkg", "__init__.py"), "w").write("print('  pkg/__init__ body runs')\n")
    open(os.path.join(d, "pkg", "util.py"), "w").write("print('  pkg.util body runs')\nX = 1\n")
    sys.path.insert(0, d)

    print("1) import pkg.util")
    import pkg.util
    print("2) import pkg.util again -> served from sys.modules, no output")
    import pkg.util
    print("names bound here: pkg =", "pkg" in dir(), "| util =", "util" in dir())
    print("sys.modules has:", sorted(k for k in sys.modules if k.startswith("pkg")))

    spec = importlib.util.find_spec("pkg.util")
    print("spec:", spec.name, "| loader:", type(spec.loader).__name__, "| file:", os.path.basename(spec.origin))
    print("finders:", [getattr(f, "__name__", type(f).__name__) for f in sys.meta_path])

    print("3) delete from sys.modules and import again")
    del sys.modules["pkg.util"]
    import pkg.util
output · Python 3.14runs offline
1) import pkg.util
  pkg/__init__ body runs
  pkg.util body runs
2) import pkg.util again -> served from sys.modules, no output
names bound here: pkg = True | util = False
sys.modules has: ['pkg', 'pkg.util']
spec: pkg.util | loader: SourceFileLoader | file: util.py
finders: ['BuiltinImporter', 'FrozenImporter', 'PathFinder']
3) delete from sys.modules and import again
  pkg.util body runs

What you see: the package __init__ runs first, then util; the second import is silent; only pkg is bound in this namespace; the finder list names the built-in, frozen and path finders; deleting the cache entry makes the body run again.

Why: sys.modules is the single source of truth for "already imported", and the loader runs the body exactly once per entry.

Java · Spring

Classes load lazily by name.

Load.txtruns offline
ClassLoader finds Foo.class
loads and links it once
static {} runs on first use

Python

Modules execute on import.

load.txtruns offline
finder -> spec -> loader
body runs once, cached in
sys.modules, then name bound

The shift: A Java class initialises on first use; a Python module's whole body runs when it is imported, which is why import-time work matters.

Land it I describe import as: check sys.modules, else ask the finders on sys.meta_path, let the loader run the body once and cache it, then bind the name, with the cache entry added before the body runs.

Likely follow-ups
"Why is the module cached before its body finishes?"

To stop two modules that import each other from looping forever. Suppose a imports b, and b imports a. When Python starts a, it first registers a new, empty module object in sys.modules, then runs the body. In the middle of that body, import b starts b, whose body says import a. Python looks in sys.modules, finds the half-built a, and hands it over. If the entry were only added at the end, this would recurse without end.

The same decision causes the famous error. If b then writes from a import A, and A is defined further down in a, the name does not exist yet, and you get the "partially initialised module" ImportError (Q72).

So it is a design for survival, not for safety: cycles do not hang, but they can still hand you a module that is only partly ready.

"What is the difference between import x and from x import y?"

Both statements import the whole module x first and cache it in sys.modules. They differ in what name they bind in your file, and when the lookup of an attribute happens.

  1. import x: binds the name x to the module object. Every use x.y looks y up at the moment of the call.
  2. from x import y: looks up x.y once, right now, and binds y to whatever object it found.

The second form freezes the answer. If someone later rebinds x.y to a different object, your y still points to the old one.

A common place this bites is testing. patch("module.func") replaces the name in module module, but a file that did from module import func already holds the original, so the patch seems to have no effect (Q135). The rule is to patch the name where it is used.

So I prefer import x with x.y(...) when a name may be patched or reassigned, and from x import y for stable names I use often.

"How are packages different from modules?"

A package is a module that can contain other modules. Technically it has a __path__ attribute, listing where its submodules live. Usually it is a folder with an __init__.py, and a folder without that file can also act as a namespace package.

The key behaviour is the order. Importing pkg.util first imports pkg, which runs pkg/__init__.py, and only then imports util. So every import of any submodule pays for everything that __init__.py imports. A package whose __init__ eagerly imports ten submodules and a heavy library makes import pkg.tiny slow, and this is a common reason for slow CLI start-up (Q74).

The habit that follows is to keep __init__.py nearly empty, or limited to a few cheap re-exports that define the public API. If you do re-export heavily, use lazy loading of the submodule. Look at the output of python -X importtime to see which package __init__ is the expensive one.

"What can go wrong with deleting from sys.modules?"

You end up with two copies of the same module, and that creates subtle bugs. Deleting the entry from sys.modules only removes the cache. Everything that already imported the module keeps a reference to the old module object. The next import creates a second one by running the body again.

The result: two sets of global variables, two copies of each class, and isinstance checks that fail, because an object made from the old class is not an instance of the new class with the same name. A module-level counter or registry is silently duplicated.

importlib.reload is gentler, as it re-runs the body inside the same module object, so old references see the new definitions of module globals. But it has its own sharp edges: objects created from old classes still use the old code, and anything the module registered elsewhere is registered twice.

My rule is to use these tools in development helpers and tests, with care, and never in production code.

Q72 · Scenario. "ImportError: cannot import name ... (most likely due to a circular import) appears only in production. Diagnose and fix."

Reveal answer

Strong answer A circular import means module a imports b while b is importing a. Because a module is added to sys.modules before its body finishes (Q71), the second import receives the half-built module. If it then asks that module for a name defined later in the file (from a import A), the name does not exist yet, and Python raises the ImportError with the "partially initialised module" hint.

Why only in production? (The error text also changed between versions: 3.12 prints "partially initialized module", 3.14 prints a "consider renaming" hint for the same cause, so search for the shape, a from a import X line inside a chain of imports.) The order of imports decides who starts first.

Locally a test imports b first and it happens to work; in production the entry point imports a first and it fails. A change in import order, a different entry point, a worker started with a different first import, or -m versus script, all change the outcome.

Diagnose by reading the full traceback: it shows the chain of imports and the file that asked for the missing name. Then fix the design.

Options, best first: move the shared piece (a type, a constant, a base class) to a third module both can import; import the module, not the name (import a then a.A at call time), which defers the lookup; import inside the function that needs it, so it runs after both modules are complete; or use TYPE_CHECKING imports for names that are only needed for annotations. A cycle is usually a sign two modules know too much about each other.

Picture it A two-module cycle that fails, and the three fixes.

The setup: Files are written to a temporary folder; each case runs in a fresh interpreter, and the last line of the error is printed.

q72_circular_import.py · Python 3.14runs offline
import os, subprocess, sys, tempfile, textwrap

VENV312 = "/home/iam100god/Desktop/AI_COURSE/.venv/bin/python"

def attempt(title, files, entry, exe=None):
    with tempfile.TemporaryDirectory() as d:
        for name, src in files.items():
            open(os.path.join(d, name), "w").write(textwrap.dedent(src))
        r = subprocess.run([exe or sys.executable, "-c", f"import {entry}; print('  ok:', {entry}.__name__)"],
                           cwd=d, capture_output=True, text=True)
        last = (r.stdout.strip() or r.stderr.strip().splitlines()[-1]).replace(d + "/", "")
        print(f"{title}\n  {last}")

CYCLE = {"a.py": "from b import B\nclass A: pass\n", "b.py": "from a import A\nclass B: pass\n"}
attempt("cycle, importing names (Python 3.14)", CYCLE, "a")
attempt("the same cycle on Python 3.12", CYCLE, "a", VENV312)

attempt("fix 1: shared third module", {
    "shared.py": "class A: pass\nclass B: pass\n",
    "a.py": "from shared import A\n",
    "b.py": "from shared import B\n"}, "a")

attempt("fix 2: import the module, use the name later", {
    "a.py": "import b\nclass A: pass\n",
    "b.py": "import a\nclass B:\n    def make(self):\n        return a.A()\n"}, "a")

attempt("fix 3: import inside the function", {
    "a.py": "from b import B\nclass A: pass\n",
    "b.py": "class B:\n    def make(self):\n        from a import A\n        return A()\n"}, "a")
output · Python 3.14runs offline
cycle, importing names (Python 3.14)
  ImportError: cannot import name 'A' from 'a' (consider renaming 'a.py' if it has the same name as a library you intended to import)
the same cycle on Python 3.12
  ImportError: cannot import name 'A' from partially initialized module 'a' (most likely due to a circular import) (a.py)
fix 1: shared third module
  ok: a
fix 2: import the module, use the name later
  ok: a
fix 3: import inside the function
  ok: a

What you see: the cycle fails on both versions, but the wording differs: Python 3.12 says cannot import name 'A' from partially initialized module 'a' (most likely due to a circular import), while 3.14 prints a different hint (consider renaming 'a.py'...) for the same cause. All three redesigns import cleanly.

Why: when a is half-built, b asks for A before a reached the line that defines it.

Cycle

Each needs the other first.

cycle.pyruns offline
# a.py
from b import B
class A: ...
# b.py
from a import A      # fails

Break it

Third module.

fixed.pyruns offline
# shared.py: A and B
# a.py
from shared import A
# b.py
from shared import B

The shift: Move what both need into a lower layer, so imports point one way only.

Land it I explain that a half-built module is handed to the second importer, so I read the traceback, then break the cycle with a shared module, module-level import x, or a local import, and I keep imports pointing one way.

Likely follow-ups
"Why does it depend on which module is imported first?"

Because the first module to start is the one left half-built when the cycle closes. Take two files that import each other. If you start from a, then b runs while a is incomplete, so b sees a partial a. If you start from b, then a runs while b is incomplete, and it is a that sees a partial b.

The two directions are not symmetric. One direction may only need names that were defined early, before the second import line, and it works. The other direction needs a name that is defined after that line and fails.

That is how the same code works on your machine and fails in production:

  1. Your test: imports b first, which happens to be the safe order.
  2. Production: the application's entry point imports a first, and the cycle hits the missing name.

Entry points, worker processes, -m versus script, and even a changed import line in an unrelated file can reorder things. That is why I fix the structure and not the order.

"What is TYPE_CHECKING for?"

It is a constant from typing that is False at run time and True for static type checkers such as mypy and pyright. Code under if TYPE_CHECKING: is therefore seen by the checker and skipped when the program runs.

orders.py
from __future__ import annotations
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from customers import Customer      # only for the checker

def owner_name(order) -> str:
    c: Customer = order.customer
    return c.name

The import vanishes at run time, so a cycle that existed only for type hints disappears. Annotations then need to be strings, or use from __future__ import annotations. In 3.14 annotations are evaluated lazily by default (PEP 649, Q122), so quotes are rarely needed.

The limit is that the name does not exist at run time. Do not use a TYPE_CHECKING import for a name you call, subclass, or use in isinstance. That would raise NameError.

"Is a local import a code smell?"

A little, but it is a legitimate tool, and I use it deliberately. An import inside a function runs only when the function is called, and by then both modules are fully loaded, so a cycle cannot hurt. It also delays the cost of a heavy library until it is needed, which helps start-up time (Q74).

The concerns are real but small. The import statement is hidden from the top of the file, so readers and tools find dependencies less easily. And each call does a lookup in sys.modules, which costs a few hundred nanoseconds. That is fine for a handler called a few times per second, and wasteful in a hot loop.

  1. Acceptable: one or two local imports, each with a one-line comment such as "avoids cycle with orders" or "heavy, rarely used".
  2. A smell: many functions needing local imports. The module structure is the real problem, and I would move shared code to a third module.
"How can I find cycles in a large codebase?"

With a tool, not by reading. Three common choices:

  1. pydeps: draws the module dependency graph, and highlights cycles, which helps to see the shape of a mess.
  2. import-linter: lets you write rules, such as "domain must not import api", and fails the build when a rule is broken. It enforces layering, not only cycles.
  3. pylint: has a cyclic-import check that you can turn on in the linter you already run.

Run one of them in CI. Then a new cycle fails the pull request, instead of failing at start-up in production on a different import order.

The better cure is the architecture. A layered design, where domain code imports nothing from services, services import domain, and the API imports services, with imports pointing only downward, prevents most cycles by construction. When you do find one, ask which module knows too much about the other, and move the shared piece down into a lower layer.

Q73. "What does if __name__ == "__main__": do, and why do spawn and forkserver multiprocessing need it?"

Reveal answer

Strong answer When a file is run as a script, Python sets its __name__ to "__main__". When the same file is imported, __name__ is the module's real name. The guard if __name__ == "__main__": therefore means "run this block only when the file is executed directly, not when it is imported". It keeps start-up code (parsing arguments, starting a server) out of imports, and lets tests and other modules import your functions safely.

multiprocessing with the spawn or forkserver start methods starts a fresh interpreter for each worker. To get your function into the worker, the child imports your main module (under the name __mp_main__). If your script starts a process pool at the top level without a guard, the child imports the module, reaches the same line, and tries to start more workers.

Python detects this and raises RuntimeError: An attempt has been made to start a new process before the current process has finished its bootstrapping phase. With fork, the child is a copy of the parent and does not re-import, which is why unguarded code used to work on Linux.

Python 3.14 changed the Linux default start method from fork to forkserver, so scripts that were sloppy for years started failing. The fix is the guard, and keeping the worker functions at module level so they can be pickled by name.

Picture it The same pool script without and with the guard, run on 3.14.

The setup: Two small scripts written to a temporary folder and run in child interpreters; the error lines are printed.

q73_main_guard.py · Python 3.14runs offline
import os, subprocess, sys, tempfile, textwrap

BODY = """
from concurrent.futures import ProcessPoolExecutor

def square(x):
    return x * x
"""
NO_GUARD = BODY + """
with ProcessPoolExecutor(2) as pool:
    print("results:", list(pool.map(square, range(4))))
"""
GUARDED = BODY + """
if __name__ == "__main__":
    with ProcessPoolExecutor(2) as pool:
        print("results:", list(pool.map(square, range(4))))
"""

def run(title, source):
    with tempfile.TemporaryDirectory() as d:
        path = os.path.join(d, "pool.py")
        open(path, "w").write(textwrap.dedent(source))
        r = subprocess.run([sys.executable, path], capture_output=True, text=True, timeout=60)
    lines = [l.strip() for l in (r.stdout + r.stderr).splitlines()]
    keep = [l for l in lines if l.startswith("results:") or "An attempt has been made" in l
            or "bootstrapping phase" in l or l.startswith("ConnectionResetError")]
    print(f"{title}: exit code {r.returncode}")
    for l in dict.fromkeys(keep):
        print("   ", l)

import multiprocessing
print("default start method here:", multiprocessing.get_start_method())
run("without the guard", NO_GUARD)
run("with the guard   ", GUARDED)
output · Python 3.14runs offline
default start method here: forkserver
without the guard: exit code 1
    An attempt has been made to start a new process before the
    current process has finished its bootstrapping phase.
    ConnectionResetError: [Errno 104] Connection reset by peer
with the guard   : exit code 0
    results: [0, 1, 4, 9]

What you see: the unguarded script fails with the "bootstrapping phase" RuntimeError (the workers re-import the module and try to start pools of their own), and the guarded script prints the results.

Why: under forkserver, worker start-up imports the main module, so every top-level statement runs again in each child unless the guard blocks it.

Java · Spring

main() is the only entry.

Main.javaruns offline
public static void main(String[] a) {
  start();
}
// importing the class runs nothing

Python

Guard marks the entry.

main.pyruns offline
def main():
    start()

if __name__ == "__main__":
    main()

The shift: Java has a dedicated entry method; Python modules are scripts, so the guard separates "run" from "import". See the main-guard idiom.

Land it I say __name__ is "__main__" only when the file is run directly, so the guard keeps import side effects out, and spawn and forkserver workers re-import the main module, which is why a pool created without it recurses and fails.

Likely follow-ups
"What does __mp_main__ mean?"

It is the name a worker process gives to the copy of your main module that it imports. With spawn or forkserver, the child starts a fresh interpreter and needs your functions, so it imports the file that started the program, but under the name __mp_main__.

That has a precise effect. In the child, __name__ is "__mp_main__", so the test __name__ == "__main__" is false, and the guarded block does not run. The rest of the module does run: imports, def and class statements. So the child can find a function such as square by name, which is how the function you submitted is unpickled and called.

Two rules follow:

  1. Define workers at module level: a function defined inside the if __name__ == "__main__": block does not exist in the child.
  2. No lambdas or local functions: pickle stores functions by name, and these have no importable name.
"How do I make python -m package runnable?"

Add a __main__.py file inside the package. When you run python -m package, Python executes that file as __main__, with the package context set, so relative imports work.

The clean layout keeps the real logic out of that file:

mytool/__main__.py
from .cli import main

if __name__ == "__main__":
    raise SystemExit(main())

The function main(argv=None) lives in cli.py. It parses arguments, does the work and returns an exit code. Because argv can be passed in, a test can call main(["--help"]) directly, with no subprocess.

The same main is also the target of a console script. In pyproject.toml, an entry such as mytool = "mytool.cli:main" under [project.scripts] makes the installer create a mytool command. So one function serves three entry points: python -m mytool, the installed command, and tests.

"Does the guard matter for fork?"

Not for the correctness of the pool on Linux with fork, since the child is a copy and does not re-import your main module. But I still write it, every time, for reasons that have nothing to do with that one case.

  1. Other tools import your script: test collectors, documentation generators, linters and IDE helpers import files to inspect them. Without the guard they would start your server.
  2. Defaults change: macOS and Windows already use spawn, and Linux moved from fork to forkserver in 3.14. Code that was sloppy for years then breaks on an upgrade.
  3. Pickling: functions defined in __main__ are pickled by reference, so the module must be safe to import.

The cost is two lines and one level of indentation. The benefit is that the same file works as a script, as a library and under every start method. I treat it like closing a file: cheap, habitual, and not worth debating.

"What else breaks when moving from fork to forkserver?"

Several things that fork gave for free are gone. A forked child is a copy of the parent's memory, so it has everything. A forkserver or spawn child starts empty and receives only what you send it.

  1. Globals set at run time: a module-level cache or setting that the parent filled is not there. The child sees only what the module's import produces.
  2. Picklable arguments: the function and its arguments are pickled and sent, so lambdas, local functions and open handles fail.
  3. No shared handles: sockets, open files and database connections are not inherited and must be opened in the worker.
  4. Import cost per worker: each worker imports your modules itself, so a pool of eight pays eight start-ups, unlike the nearly free copy of fork.

The remedy for state is the pool's initializer= argument: a function that runs once in each worker and opens connections or loads a model. Pass identifiers, not live objects, and let the worker rebuild what it needs.

Q74 · Scenario. "Your command-line tool takes 1.8 seconds to start. Find the cause and fix it."

Reveal answer

Strong answer Measure, do not guess. Run python -X importtime -m mytool --help. It prints, on stderr, one line per imported module with its self time and cumulative time in microseconds. Sort by cumulative and the heavy imports are at the top. Python start-up itself is about ten to twenty milliseconds; the rest is yours and your dependencies'.

Typical causes: a heavy third-party library imported at the top of every module although only one command uses it (pandas, boto3, torch, big ORMs); work done at import time (building tables, reading files, opening connections, compiling many regexes); a package __init__ that imports all its submodules; and plugin discovery that imports every plugin at start.

Fixes. Import lazily: move the heavy import inside the function that needs it, so --help and --version never pay. In 3.15 write lazy import pandas at module scope; the module is loaded on first use (PEP 810; module level only, and the global switch -X lazy_imports or PYTHON_LAZY_IMPORTS exists). Remove import-time work: make it a function called when needed. Slim __init__. Then re-measure and record the before and after in the pull request.

Picture it A CLI with a slow dependency, measured with -X importtime, then fixed with a local import and with 3.15's lazy import.

The setup: slowdep.py builds a large table at import (a stand-in for a heavy library). cli.py imports it at the top but only the report command needs it.

q74_slow_startup.py · Python 3.14runs offline
import os, subprocess, sys, tempfile, textwrap, time

SLOWDEP = "TABLE = [i * i % 97 for i in range(3_000_000)]\n"      # work at import time
EAGER = "import slowdep\nimport sys\nif sys.argv[1] == 'report':\n    print(len(slowdep.TABLE))\nelse:\n    print('version 1.0')\n"
LOCAL = "import sys\nif sys.argv[1] == 'report':\n    import slowdep\n    print(len(slowdep.TABLE))\nelse:\n    print('version 1.0')\n"
LAZY = "lazy import slowdep\nimport sys\nif sys.argv[1] == 'report':\n    print(len(slowdep.TABLE))\nelse:\n    print('version 1.0')\n"
U = "/home/iam100god/.local/share/uv/python/"
PY315 = U + "cpython-3.15-linux-x86_64-gnu/bin/python3.15"

def timed(exe, script, arg, cwd):
    t = time.perf_counter()
    subprocess.run([exe, script, arg], cwd=cwd, capture_output=True, check=True)
    return (time.perf_counter() - t) * 1000

with tempfile.TemporaryDirectory() as d:
    for name, src in (("slowdep.py", SLOWDEP), ("eager.py", EAGER), ("local.py", LOCAL), ("lazy.py", LAZY)):
        open(os.path.join(d, name), "w").write(src)

    r = subprocess.run([sys.executable, "-X", "importtime", "eager.py", "--version"], cwd=d, capture_output=True, text=True)
    rows = sorted(((int(l.split("|")[1]), l.split("|")[2].strip()) for l in r.stderr.splitlines()[1:]), reverse=True)
    print("python -X importtime eager.py --version  (top 3 by cumulative time)")
    for us, name in rows[:3]:
        print(f"   {us / 1000:8.1f} ms  {name}")

    print()
    print(f"{'variant':34}{'--version':>12}{'report':>12}")
    for label, exe, script in (("3.14 eager top-level import", sys.executable, "eager.py"),
                               ("3.14 import inside the function", sys.executable, "local.py"),
                               ("3.15 `lazy import`", PY315, "lazy.py")):
        a = min(timed(exe, script, "--version", d) for _ in range(3))
        b = min(timed(exe, script, "report", d) for _ in range(3))
        print(f"{label:34}{a:10.0f} ms{b:10.0f} ms")
output · Python 3.14runs offline
python -X importtime eager.py --version  (top 3 by cumulative time)
      237.5 ms  slowdep
        5.2 ms  site
        4.0 ms  encodings

variant                              --version      report
3.14 eager top-level import              257 ms       200 ms
3.14 import inside the function           13 ms       201 ms
3.15 `lazy import`                        12 ms       201 ms
# measured on the course machine; your numbers will differ

What you see: -X importtime points at slowdep. The eager version pays for the table even for --version; both the local import and 3.15's lazy import make --version fast, and report still pays when it really needs the module.

Why: the cost belongs to the commands that use the dependency, not to every command.

Eager

Everyone pays at start-up.

eager.pyruns offline
import pandas
def version():
    print("1.0")     # still slow

Lazy

Pay when first used.

lazy.pyruns offline
lazy import pandas   # 3.15
# or: import inside report()
def version():
    print("1.0")     # fast

The shift: Move the cost from process start to the first real use. See the lazy-import idiom.

Land it I measure with -X importtime, find the heavy module and import-time work, and defer it with a function-level import or 3.15's lazy import, then record the before and after times.

Likely follow-ups
"How do I read -X importtime output?"

Each line is printed to stderr in the form import time: self [us] | cumulative | imported package. All times are microseconds.

  1. Self: the time spent running that module's own body, excluding what it imported.
  2. Cumulative: the self time plus every module it pulled in.
  3. Indentation: the name is indented to show nesting, so you can see which import brought which.

To read it, I first sort by cumulative time to find the expensive branches of the tree, for example one top-level import that costs 600 ms in total. Then I look inside that branch and sort by self time, to find the module that is itself doing the work, such as building tables or compiling many regular expressions.

Because the output goes to stderr and a big program prints hundreds of lines, redirect it: python -X importtime -m mytool --help 2> imports.txt. Then sort the file with a tool of your choice. Always read the first run and a second run, because the first one may include compiling to .pyc.

"What are the rules of PEP 810's lazy import?"

PEP 810 adds two forms: lazy import x and lazy from x import y. Instead of loading the module, they bind a lightweight proxy at module scope. The real import happens the first time the name is used.

  1. Module level only: inside a function, a class body or a try/except block it is a SyntaxError.
  2. Global control: the switch -X lazy_imports, or the environment variable PYTHON_LAZY_IMPORTS, changes the default behaviour for the whole run.
  3. Errors move: import errors and import-time side effects now happen at first use, not at start-up.

That last point is the trade-off. A missing dependency, or a module that fails when imported, shows up late and far from the line that caused it, perhaps in the middle of a request. For a CLI that is acceptable, since --help never loads the heavy part. For a service I would add a start-up check that touches the important lazy imports.

Confirm details against the 3.15 documentation.

"What if the slowness is not imports at all?"

Then the time is not in imports, and I switch to a profiler. Run the start-up under cProfile with python -m cProfile -s cumtime tool.py --help, and read the top of the list for the biggest cumulative costs.

The typical findings are all work done too early:

  1. Module-level work: a file read, a network call or a big table built when the module is imported.
  2. Work before argument parsing: loading configuration, connecting to a service or scanning plugin folders in main() before the arguments are even checked.
  3. Eager plugin discovery: importing every plugin to list its name.

The fix is to parse the arguments first and do the minimum for the cheap commands. --help and --version should answer without opening the config or the network. Then move expensive set-up into the command that needs it.

Python's own start-up (about 13 ms here, Q61) is rarely the problem. If a 1.8 s start-up has a 13 ms floor, the other 1.79 s is ours to find.

"Does a .pyc cache help?"

A little, and it is not where the big gain is. A .pyc file saves the compile step: reading, parsing and generating bytecode from the source. It does not save running the module body. Every imported module still executes its top-level statements, creates its functions and classes, and imports its own imports.

So for a tool that imports pandas and boto3, the cache is already helping with compilation, and the 1.8 s that remains is mostly execution of those bodies. Importing less will give you far more than caching the compile.

Two practical notes. For tools installed with pip, the .pyc files are created at install time, so users do not pay the first-run cost. In containers with a read-only filesystem, run python -m compileall at build time, so the first run does not compile everything (Q64).

The order of importance is clear: avoid importing, then import lazily, and only then think about the compile cache.

Q75. "What is the GIL, and what exactly does it protect?"

Reveal answer

The real test Whether you say "it protects the interpreter's internal state, mainly reference counts, not your program's data".

Strong answer The GIL (global interpreter lock) is a mutex inside CPython: only one thread at a time may execute Python bytecode in a given interpreter. A thread must hold the GIL to run Python code; it hands it over on a timer (the switch interval, 5 milliseconds by default, sys.getswitchinterval()) and whenever it blocks.

What it protects is the interpreter itself: the object model and above all reference counts (Q11). Every assignment adds or removes a reference, and incrementing a plain integer from two threads without synchronisation can lose an update and corrupt memory management. One big lock made all of that safe cheaply, and made C extensions easy to write.

What it does not protect is your data and your invariants. A thread can be switched out between any two bytecode instructions, so balance -= n (read, subtract, write: several instructions, Q78) or "check, then act" sequences can interleave with another thread. Individual operations such as list.append are atomic in practice, but compound ones are not. You still need locks for your own critical sections.

The effect on performance: threads do not run Python code in parallel, so CPU-bound threaded code gains nothing (Q77). Threads still help when they wait: I/O and time.sleep release the GIL (Q76).

Picture it Two threads that each check a balance and then withdraw, with the GIL present, and the lock that fixes it (the unlucky timing is forced so that it shows every time).

The setup: A check-then-act withdrawal. A Barrier makes both threads pass the check before either updates, which is the unlucky interleaving that a thread switch can produce on its own.

q75_gil_protects.py · Python 3.14runs offline
import sys, threading, time

print("switch interval:", sys.getswitchinterval(), "s | GIL enabled:", sys._is_gil_enabled())

def run(use_lock):
    state = {"balance": 100}
    lock = threading.Lock()

    rendezvous = threading.Barrier(2)          # forces both threads to finish the check first

    def withdraw(n):
        def body():
            if state["balance"] >= n:          # check
                if not use_lock:
                    rendezvous.wait()          # both threads have now passed the check
                state["balance"] -= n          # act
        if use_lock:
            with lock:
                body()
        else:
            body()

    threads = [threading.Thread(target=withdraw, args=(80,)) for _ in range(2)]
    for t in threads: t.start()
    for t in threads: t.join()
    return state["balance"]

print("without a lock, two withdrawals of 80 from 100 leave:", run(False))
print("with a lock                                  leaves:", run(True))
output · Python 3.14runs offline
switch interval: 0.005 s | GIL enabled: True
without a lock, two withdrawals of 80 from 100 leave: -60
with a lock                                  leaves: 20

What you see: with the GIL on, the unlocked version still overdraws (balance -60): both threads passed the check before either updated. I forced that timing with the barrier; in real code it happens rarely and unpredictably, which is worse. The locked version refuses the second withdrawal and leaves 20.

Why: the GIL guarantees the interpreter will not corrupt itself; it does not make your multi-step logic atomic.

Java · Spring

Real parallel threads.

Th.txtruns offline
JVM threads run in parallel;
shared data needs synchronized
/ locks /atomics

Python

Threads take turns.

th.txtruns offline
one thread runs bytecode at a
time; I/O releases the lock;
your invariants still need Lock

The shift: Java threads run truly in parallel and need locks for everything shared; Python threads take turns but still need locks for multi-step logic.

Land it I say the GIL lets one thread run Python bytecode at a time to keep the interpreter's internals, especially reference counts, consistent, and it does not make my compound operations atomic, so I still lock my own invariants.

Likely follow-ups
"Why does CPython have a GIL at all?"

Mostly history, plus a real engineering trade-off. CPython manages memory with reference counting: every object has a counter that goes up and down as names point to it. Those updates happen constantly, on almost every line. If two threads could update the same counter at once without protection, a count could be wrong, and an object might be freed while still in use, or leak.

There were two ways to make this safe. A lock on every object makes every assignment slower. One global lock is cheap, since a thread takes it once and runs many bytecodes. That also made C extensions easy to write, since they could assume that no other thread touched Python objects while they ran.

The design dates from the 1990s, when almost every machine had one core, so the cost of the one big lock was invisible. The cost appeared later, as multi-core machines became normal.

Removing it required a new scheme: biased reference counting, immortal objects and per-object locks. That is the free-threaded build (Q79).

"Which operations are atomic under the GIL?"

The single built-in operations that finish inside one step of the interpreter. list.append, dict[key] = value and queue.Queue.put cannot be torn in half, because the whole operation runs while the thread holds the GIL.

Compound operations are not atomic, because the thread can be switched out between two instructions:

not atomic
x += 1                       # load, add, store: three steps
d[k] = d.get(k, 0) + 1       # read, add, write
if k not in d: d[k] = []     # check, then act

Each of these can interleave with another thread and lose an update.

Do not rely on "it is atomic in CPython" for your design. It is an implementation detail, and on the free-threaded build your own invariants are no longer protected by the GIL, even though the built-in types stay internally safe. For shared counters and state, use a threading.Lock, a queue.Queue, or let one thread own the data and send it messages.

"What is the switch interval?"

It is the time after which a thread that holds the GIL is asked to give it up, if another thread is waiting. The default is 5 ms, read with sys.getswitchinterval() and set with sys.setswitchinterval.

The details:

  1. It is a request: the running thread sees a flag and drops the GIL at the next bytecode boundary, not in the middle of an instruction.
  2. Blocking calls skip it: I/O, time.sleep and lock waits release the GIL at once, without waiting for the interval.
  3. The trade-off: a shorter interval gives faster switching, so better latency for waiting threads, but more switching cost. A longer one gives higher throughput and worse latency.

Take a worker computing for 100 ms while a second thread waits: with 5 ms, the second one gets its turn within about 5 ms of asking.

I leave the value alone unless I have measured a latency problem that a different value fixes. In most programs the default is fine.

"Do multiple interpreters have separate GILs?"

Yes, since Python 3.12. Each sub-interpreter can have its own GIL (PEP 684), so several interpreters in one process can run Python code at the same time on different cores. Python 3.14 exposes them to Python code through concurrent.interpreters and an InterpreterPoolExecutor (PEP 734).

The key is isolation. Objects are not shared between interpreters, so there is no shared reference count to protect, and no need for a single lock across them. Data moves by copying or by a few shareable types, much as it does between processes.

That makes sub-interpreters a middle option (Q97). They are lighter than processes, with less memory and quicker start-up, and they give true parallelism for CPU work. They are more restricted than threads, since you cannot pass arbitrary objects, and some C extensions do not support them yet.

The free-threaded build takes the opposite approach: it removes the GIL inside one interpreter and keeps sharing objects between threads.

Q76. "When does CPython release the GIL?"

Reveal answer

Strong answer A thread gives up the GIL in four situations. 1. When it makes a blocking call: file and socket I/O, time.sleep, waiting on a lock, subprocess waits, and database drivers that wait on the network. The interpreter drops the GIL before the system call and re-acquires it after.

2. When a C extension releases it on purpose: numeric libraries such as NumPy release it for long array operations; hashlib and zlib release it for large buffers; re does not for ordinary use. 3. On the switch interval: if another thread is waiting and the running one has held the GIL for about 5 ms, it is asked to yield at the next bytecode boundary. 4. At thread end.

This explains the performance rules. Threads are good for waiting (I/O-bound work): while one thread waits for a socket, another runs Python. Threads do not speed up pure-Python computation. Threads can speed up work inside C code that releases the GIL, which is why a thread pool over hashlib.sha256 of big buffers scales on several cores.

A C extension has to ask for the release explicitly (Py_BEGIN_ALLOW_THREADS); calling into one that does not blocks all other threads for the duration of the call. That is why a single slow C call inside an async or threaded service can freeze everything.

Picture it Four sleeping threads overlap, four hashing threads on big buffers overlap, four pure-Python loops do not.

The setup: The same four-thread pool on three workloads; the times are compared with a serial run.

q76_gil_release.py · Python 3.14runs offline
import hashlib, time
from concurrent.futures import ThreadPoolExecutor

def sleeper():
    time.sleep(0.25)

BUF = b"x" * 64_000_000
def hasher():
    hashlib.sha256(BUF).hexdigest()          # large buffer: hashlib releases the GIL

def python_loop():
    total = 0
    for i in range(2_500_000):               # pure Python: holds the GIL
        total += i % 7
    return total

def compare(label, fn, n=4):
    t = time.perf_counter()
    for _ in range(n):
        fn()
    serial = time.perf_counter() - t
    t = time.perf_counter()
    with ThreadPoolExecutor(n) as pool:
        for f in [pool.submit(fn) for _ in range(n)]:
            f.result()
    threaded = time.perf_counter() - t
    print(f"{label:22} serial {serial:5.2f} s | 4 threads {threaded:5.2f} s | speed-up x{serial / threaded:3.1f}")

compare("time.sleep", sleeper)
compare("hashlib on 64 MB", hasher)
compare("pure Python loop", python_loop)
output · Python 3.14runs offline
time.sleep             serial  1.00 s | 4 threads  0.25 s | speed-up x4.0
hashlib on 64 MB       serial  0.16 s | 4 threads  0.05 s | speed-up x3.6
pure Python loop       serial  0.34 s | 4 threads  0.57 s | speed-up x0.6
# measured on the course machine; your numbers will differ

What you see: sleeping threads overlap almost perfectly (about 4x), hashing big buffers also speeds up because hashlib releases the GIL, and the pure-Python loop gets no speed-up.

Why: only the first two do their waiting or computing outside the interpreter, with the GIL released.

Pure Python

Holds the GIL.

pure.pyruns offline
def work():
    for i in range(N):
        total += i % 7
# threads take turns

GIL released

Real overlap.

released.pyruns offline
def work():
    hashlib.sha256(buf)   # C code
    time.sleep(0.2)       # blocking

The shift: Threads scale when their time is spent outside the interpreter, and not when it is spent running bytecode.

Land it I say the GIL is released on blocking calls, by C extensions that opt out of it, and at the switch interval, so threads help I/O and GIL-releasing C code but not pure-Python computation.

Likely follow-ups
"Does requests or a database driver release the GIL?"

Yes for the waiting part, no for the Python part. When requests sends a request and waits for the reply, the thread is inside a socket call, and the interpreter lets go of the GIL before that system call. Another thread can run Python while this one sleeps in the kernel.

When the reply arrives, the thread takes the GIL back and runs ordinary Python to parse headers and decode JSON. That part holds the lock.

For a typical call, almost all the time is waiting. Take 200 ms on the wire and 2 ms of parsing: 99 percent of the time is lock-free, so 50 threads can overlap their waits and finish about 50 calls in a little over 200 ms.

Database drivers behave the same way. Drivers written in C, such as psycopg2 and mysqlclient, release the lock during the query. A pure-Python driver releases it inside its socket calls.

The trap is a task that fetches a huge result and then processes it in Python. The processing part still runs one thread at a time.

"Does NumPy release the GIL?"

Mostly yes, for the long calls. A mathematical operation on a large array runs in C loops, and NumPy releases the GIL around those loops, so two threads can work on two big arrays on two cores at the same time.

The key word is large. Each NumPy call also has a fixed cost in Python: looking up the function, checking types and building the result object. That part holds the GIL. For an array of 10 numbers, the overhead is most of the time and threads gain nothing. For an array of 10 million numbers, the C loop dominates and threads can scale.

Another detail is that some linear algebra routines call BLAS libraries (OpenBLAS, MKL) that start their own native threads. Then you can have your 4 Python threads each starting 12 BLAS threads, which oversubscribes the machine. The library has settings for this, such as OMP_NUM_THREADS.

I would test with a real array size and 1, 2, 4 threads before relying on it.

"What does re do?"

The built-in re engine holds the GIL while it matches, so threads running regular expressions take turns instead of running together. A pool of 4 threads matching log lines is about as slow as 1 thread, plus a little overhead.

The reason is simple. The matcher is C code, but it works directly on Python string objects and is not written to run without the lock. The third-party regex module can release the GIL in some cases, but I would verify that for the exact call, since it depends on the options and the string type.

If regular expressions are the bottleneck, I have three options in order:

  1. Simplify: anchor the pattern, avoid nested repeats, or use plain str.find or str.startswith when a pattern is not needed.
  2. Split across processes: each process gets a big chunk of the file, not one line.
  3. Use a different tool: a native engine that is built for it.

Separately, a pattern like (a+)+b can take exponential time on some inputs. That is a bigger risk than the GIL.

"How do I know if a call releases it?"

There are three ways, from cheapest to most reliable. First, read the documentation: standard-library pages for hashlib, zlib and time.sleep say that the GIL is released, and NumPy documents it for many functions.

Second, measure it, which settles the question for your exact input. Run the same call over a fixed number of items in 1 thread, then in 4 threads, and compare wall-clock time. A result close to 1 times means the lock is held. A result near 3 to 4 times means the call releases it.

Third, if you write the extension, you decide: in C you wrap the long section in Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS, and in Cython you use with nogil:. Inside that section you must not touch any Python object.

A warning about the measurement: use big enough inputs. Tiny calls spend their time on call overhead, which holds the lock, and give a misleading answer. On a free-threaded build the question disappears, since there is no GIL to release (Q79).

Q77 · Scenario. "Four threads made a CPU-bound job no faster. Explain with numbers, then fix it."

Reveal answer

Strong answer The job is pure-Python computation, so every thread needs the GIL to run bytecode (Q75), and only one can hold it. Four threads do not run four times as fast; they take turns, with the same total work plus the cost of switching. The result is no gain, and often a small loss from lock hand-offs.

The numbers have a simple model. If one task takes T seconds, four tasks on one thread take 4T. On four threads with a GIL, they still take about 4T (plus overhead), because the interpreter executes one thread's bytecode at a time.

On four processes, each with its own interpreter and GIL, they take about T plus start-up and data-transfer cost. On the free-threaded build, four threads can each run on a core, so about T again, though each thread runs somewhat slower than on the normal build (Q79).

Fix, in order: use processes (ProcessPoolExecutor) for CPU-bound Python, with big enough units of work that the transfer cost is small (Q95); or move the hot loop into C (NumPy, Cython, Rust) that releases the GIL (Q108); or, if your dependencies support it, trial the free-threaded build (Q80); or try concurrent.interpreters (Q97). Do not add more threads.

Picture it The same four CPU-bound tasks run one after another, in four threads and in four processes, on 3.14 with the GIL and on 3.14t without it.

The setup: Each task is a pure-Python loop of 3 million iterations. A parent script runs a child in each interpreter and prints the times.

q77_threads_cpu.py · Python 3.14runs offline
import subprocess, textwrap

U = "/home/iam100god/.local/share/uv/python/"
BUILDS = {"3.14 (GIL)": U + "cpython-3.14.7-linux-x86_64-gnu/bin/python3.14",
          "3.14t (no GIL)": U + "cpython-3.14.7+freethreaded-linux-x86_64-gnu/bin/python3.14t"}

child = textwrap.dedent("""
    import sys, time
    from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor

    def task(_):
        total = 0
        for i in range(3_000_000):
            total += (i * i) % 7
        return total

    def timed(make_pool):
        t = time.perf_counter()
        if make_pool is None:
            for i in range(4):
                task(i)
        else:
            with make_pool() as pool:
                list(pool.map(task, range(4)))
        return time.perf_counter() - t

    if __name__ == "__main__":
        serial = min(timed(None) for _ in range(2))
        threads = min(timed(lambda: ThreadPoolExecutor(4)) for _ in range(2))
        procs = min(timed(lambda: ProcessPoolExecutor(4)) for _ in range(2))
        print(f"{serial:.2f} {threads:.2f} {procs:.2f}")
""")

import os, tempfile
with tempfile.TemporaryDirectory() as d:
    script = os.path.join(d, "child.py")
    open(script, "w").write(child)                       # process pools need a real file to re-import
    print(f"{'build':16}{'4 tasks serial':>16}{'4 threads':>12}{'4 processes':>14}")
    for name, exe in BUILDS.items():
        out = subprocess.run([exe, script], capture_output=True, text=True)
        serial, threads, procs = out.stdout.split()
        print(f"{name:16}{serial + ' s':>16}{threads + ' s':>12}{procs + ' s':>14}")
output · Python 3.14runs offline
build             4 tasks serial   4 threads   4 processes
3.14 (GIL)                0.76 s      1.88 s        0.22 s
3.14t (no GIL)            0.85 s      0.23 s        0.26 s
# measured on the course machine (12 cores); your numbers will differ; this is a different, smaller workload than the primer's section 05 benchmark

What you see: on the GIL build the four threads are no faster than doing the tasks one after another; here they were much slower (1.88 s against 0.76 s), while four processes cut the time to 0.22 s. On the free-threaded build the same threaded code gets close to the process speed, with no data copying.

Why: threads share one interpreter; with a GIL they alternate, without one they run in parallel. Processes always run in parallel because they have separate interpreters.

Threads on a GIL build

Take turns.

gil.pyruns offline
with ThreadPoolExecutor(4) as p:
    list(p.map(cpu_task, jobs))
# about the same as one thread

Processes

One interpreter each.

procs.pyruns offline
with ProcessPoolExecutor(4) as p:
    list(p.map(cpu_task, jobs))
# about 4x faster on 4 cores

The shift: Replace "more threads" with "more interpreters": processes, sub-interpreters, or the free-threaded build.

Land it I explain that the GIL lets one thread run bytecode at a time, quote the measured serial, thread and process times, and fix it with processes or native code, or a trial of the free-threaded build, not with more threads.

Likely follow-ups
"What were the primer's numbers, and why do mine differ?"

The numbers differ because the workload differs, so I start by saying which workload each number belongs to. The chapter's section 05 benchmark pushed 400,000 orders through CPU-bound pricing rules.

  1. Normal build 3.14: 0.70 s on one thread and 1.04 s on four threads. That is about 49 percent slower with four threads, because the threads take turns on the GIL and pay for each hand-off.
  2. Free-threaded 3.14t: 0.84 s on one thread and 0.25 s on four. That is about 3.4 times faster than its own one-thread run.

The table above this question uses a different, smaller loop, so its seconds are different. What carries over is the shape: with a GIL, four threads give no gain, and without one they give a large gain.

If the interviewer asks why yours differ, I say the loop length, the machine's cores and the Python version all change the absolute seconds. I would never compare numbers from two different programs; I would re-run both builds on the same code.

"Why can threads be slower than serial?"

Because they add work and remove nothing. Four threads still run only one at a time, so the total computation is the same, and the switching is extra.

Each time the running thread has held the GIL for about 5 ms (the switch interval, sys.getswitchinterval()) and another thread is waiting, a request to give it up is made. The thread must release the lock, wake the other thread through the operating system, and the other must take the lock. Each hand-off costs microseconds, and the data the new thread needs may not be in that core's cache.

The cost depends on the loop. The pricing benchmark lost about 49 percent, going from 0.70 s to 1.04 s. The smaller loop in the table above lost more, from 0.76 s to 1.88 s, because the threads fought over the lock almost constantly.

So a slowdown is not strange. It is why I will not accept "we added threads" as a fix without a before and after timing on the real workload.

"What size of task makes processes worth it?"

The task should be big enough that overhead is a small fraction of it. I use a rough rule: at least tens of milliseconds, and preferably a few hundred, for each unit of work sent to a worker.

Here is the arithmetic. Say sending a task and getting the result back costs about 1 ms (pickling, the pipe, unpickling), and the work takes 100 ms. Overhead is 1 percent, so four workers give close to 4 times. If the work takes 1 ms, overhead equals the work, and four workers give about 2 times at best, with a lot of CPU spent on copying.

overhead arithmetic (assumed 1 ms per task)runs offline
work 100 ms: overhead 1 / 101 = about 1 percent
work   1 ms: overhead 1 / 2   = 50 percent

The fix for small items is batching: send 500 items at a time (chunksize in map, Q95). Also keep the arguments small; a big object pickled for each task can cost more than the compute.

"Does it matter that the machine has 12 cores?"

Yes, but only as a ceiling. Twelve cores do not make the job twelve times faster. The most you can gain is limited by the number of independent tasks, and the speed-up is limited by overhead and by any serial part of the program.

With four tasks, a pool of four processes is already enough. Eight workers would leave four idle, and more processes than cores just compete for the CPU and use more memory.

To size a pool I read the CPU count the program is allowed to use. os.process_cpu_count() (3.13 and later) respects the process's CPU affinity, while os.cpu_count() returns the machine's total. In a container, the quota can be much smaller than the host's core count, so on a 12-core host with a limit of 2 CPUs, 12 workers will be throttled and slower than 2.

I also leave a core for the parent process and the operating system when response time matters. And I check the speed-up by measurement: 1, 2, 4 workers, and see where the curve flattens.

Q78. "Does the GIL make counter += 1 thread-safe?"

Reveal answer

The real test Whether you answer "no, it is several bytecodes" and can still honestly report that the race is hard to see on the GIL build.

Strong answer No. counter += 1 is not one operation: it loads the value, adds 1, and stores the result, as separate bytecode instructions (Q62, dis below). The GIL can switch threads between any two instructions, so two threads can both load the same value and both store value + 1, losing one increment.

The honest nuance: on the normal build the window is narrow. The interpreter only considers switching at certain points (about every 5 ms, and at specific instructions), so the load-add-store sequence usually completes before a switch. Four threads each adding a million times often produce the correct total, which makes people believe it is safe. It is not guaranteed; it is luck that depends on the version and the loop. Python 3.10 and later made switches even rarer at some instructions, which hides the bug further.

On the free-threaded build there is no GIL, threads really run at the same time, and the race shows immediately: millions of lost updates. The fix on every build is the same: protect the update with a threading.Lock, or avoid shared mutable counters (per-thread counters merged at the end, queue.Queue, itertools.count() for unique ids).

Picture it The bytecode, then four threads times one million increments with and without a lock, on 3.14 and on 3.14t.

The setup: A parent script runs a child in each build. A second test widens the read-to-write window with a time.sleep(0) to show the race on the GIL build too.

q78_counter_race.py · Python 3.14runs offline
import dis, subprocess, textwrap

def bump():
    global counter
    counter += 1
dis.dis(bump)
print()

U = "/home/iam100god/.local/share/uv/python/"
BUILDS = {"3.14 (GIL)": U + "cpython-3.14.7-linux-x86_64-gnu/bin/python3.14",
          "3.14t (no GIL)": U + "cpython-3.14.7+freethreaded-linux-x86_64-gnu/bin/python3.14t"}

child = textwrap.dedent("""
    import threading, time
    N, T = 1_000_000, 4
    counter = 0
    lock = threading.Lock()

    def plain():
        global counter
        for _ in range(N):
            counter += 1

    def locked():
        global counter
        for _ in range(N):
            with lock:
                counter += 1

    def widened():
        global counter
        for _ in range(5_000):
            seen = counter           # read
            time.sleep(0)            # offer a thread switch in the middle
            counter = seen + 1       # write

    def run(fn):
        global counter
        counter = 0
        threads = [threading.Thread(target=fn) for _ in range(T)]
        for t in threads: t.start()
        for t in threads: t.join()
        return counter

    results = [("plain +=", run(plain), N * T), ("with lock", run(locked), N * T), ("widened window", run(widened), 5_000 * T)]
    for label, got, want in results:
        print(f"  {label:15} expected {want:>9,}  got {got:>9,}  lost {want - got:>9,}")
""")

for name, exe in BUILDS.items():
    print(name)
    print(subprocess.run([exe, "-c", child], capture_output=True, text=True).stdout.rstrip())
output · Python 3.14runs offline
  3           RESUME                   0

  5           LOAD_GLOBAL              0 (counter)
              LOAD_SMALL_INT           1
              BINARY_OP               13 (+=)
              STORE_GLOBAL             0 (counter)
              LOAD_CONST               1 (None)
              RETURN_VALUE

3.14 (GIL)
  plain +=        expected 4,000,000  got 4,000,000  lost         0
  with lock       expected 4,000,000  got 4,000,000  lost         0
  widened window  expected    20,000  got     5,000  lost    15,000
3.14t (no GIL)
  plain +=        expected 4,000,000  got 1,285,048  lost 2,714,952
  with lock       expected 4,000,000  got 4,000,000  lost         0
  widened window  expected    20,000  got     5,239  lost    14,761
# measured on the course machine (12 cores); your numbers will differ

What you see: the bytecode shows separate load, add and store instructions for the global. On the GIL build the plain loop usually loses nothing but the widened window loses many updates; on the free-threaded build the plain loop loses millions. The lock version is exact on both.

Why: the lost update needs two threads to read the same value before either writes; the GIL makes that rare, and removing it makes it common.

Looks safe

Often right, never guaranteed.

racy.pyruns offline
def hit():
    global counter
    counter += 1
# load, add, store: 3 steps

Safe

Lock or no sharing.

safe.pyruns offline
def hit():
    global counter
    with lock:
        counter += 1

The shift: "It passed the test" is not "it is atomic"; the lock states the intent and works on every build.

Land it I say no: += is load, add, store, the GIL only makes the window small on the normal build and invisible in tests, the free-threaded build exposes it, and the fix is a lock or not sharing.

Likely follow-ups
"What were the primer's numbers for this?"

The chapter's section 05 test ran four threads, each doing one million counter += 1, and the expected total was 4,000,000. On 3.14 with the GIL it printed the correct total, so no updates were lost in normal runs. On 3.14t it lost about 2.9 million updates.

The table above this question is my own run of the same idea. On the free-threaded build the lost count changes on each run, depending on how the threads interleave. So I say "millions lost", not an exact figure.

The widened-window row in the table is the most useful. It adds a tiny pause between the load and the store, and then even the GIL build loses updates. That shows the normal build was never safe, only lucky: the load-add-store window is short, so a switch rarely lands inside it.

The lesson I draw is that a test passing on the GIL build proves very little about thread safety.

"Which counter options exist?"

There are six, and they trade simplicity, speed and scope.

  1. Lock: with lock: counter += 1. Simple and correct, and the right default.
  2. Per-thread counters: each thread increments its own, and you add them at the end. Nothing is shared during the work, so it is the fastest.
  3. itertools.count: next(c) gives the next number as one C call, so two threads never get the same value in CPython. Good for unique ids.
  4. queue.Queue: pass events to one thread that owns the total.
  5. multiprocessing.Value: for processes, with its built-in lock held around the whole update.
  6. A library atomic: if you really need lock-free counting.

I pick per-thread counters for metrics that are read now and then, and a lock for anything where the exact value is needed at every moment. Metrics libraries use per-thread buckets for this reason.

"What is the cost of the lock?"

An uncontended lock is cheap: acquiring and releasing it takes on the order of tens to a hundred nanoseconds. A plain counter += 1 is a few tens of nanoseconds, so the locked version is several times slower per update, which matches the "with lock" row in the table above.

The real cost appears under contention. When many threads want the same lock, the losers go to sleep and are woken later, and each wake-up costs microseconds. Four threads hammering one lock can be slower than one thread alone.

The rules I follow:

  1. Keep the section tiny: only the read-modify-write, never I/O or a long computation.
  2. Do not share if you can avoid it: one counter per thread, merged at the end, removes the lock completely.
  3. Batch: add up 1,000 locally, then take the lock once to add the total.

Correctness is worth the cost, but the cheapest lock is the one you do not need.

"Do built-in types become unsafe on the free-threaded build?"

No. The built-in containers stay safe at the operation level. A single list.append, dict[k] = v or set.add uses a small per-object lock inside the interpreter, so the container is not corrupted and the program does not crash.

What changes is your own logic. Take if k not in d: d[k] = compute(). Two threads can both pass the check, so both compute and one overwrites the other. This was already a race on the GIL build, but switching rarely landed between the two lines, so it hid for years. Without a GIL it shows up quickly.

Another example is iterating over a list while another thread appends to it. Each single step is safe, but the combined result may skip or repeat items.

So the answer I give is: memory safety is kept, atomicity of multi-step logic never existed. For a rollout I search for shared mutable state, add a lock around each multi-step update, and run a stress test (Q80).

Q79. "What is free-threaded Python (3.13/3.14t), what does it cost, and is it ready for production?"

Reveal answer

Strong answer Free-threaded Python is a CPython build without the GIL (PEP 703), so threads run Python code truly in parallel on several cores. Python 3.13 added it as experimental. Python 3.14 made it officially supported (PEP 779): the maintainers commit to it, but it is still a separate build (python3.14t, with a t suffix in the ABI), not the default. sys._is_gil_enabled() tells you which you have.

How it works, in a sentence: reference counting is made thread-safe with biased reference counts (the owning thread updates cheaply, others use atomic operations), immortal objects skip counting, built-in containers use per-object locks, and the memory allocator is thread-aware.

Costs: single-threaded code runs somewhat slower than on the normal build (I measured it below, same loop, one thread); memory use is a little higher; C extensions must be rebuilt and declared thread-safe (a module that does not declare it makes the interpreter turn the GIL back on, with a warning); and bugs hidden by the GIL appear (Q78).

Ready? The language and standard library are supported; the question is your dependency stack. For a CPU-heavy service whose libraries have free-threaded wheels, it is worth a controlled trial (Q80). For a typical I/O-bound web service it brings little, since threads already overlap waiting and asyncio does the rest. Treat it as a tool for CPU-bound threaded code, not as a default.

Picture it Which builds have the GIL, how to turn it back on, and the single-thread cost on this machine.

The setup: A parent script runs the same one-thread loop on both builds and also reports the GIL state, including PYTHON_GIL=1 on the free-threaded build.

q79_free_threaded.py · Python 3.14runs offline
import os, subprocess, textwrap

U = "/home/iam100god/.local/share/uv/python/"
GIL = U + "cpython-3.14.7-linux-x86_64-gnu/bin/python3.14"
FREE = U + "cpython-3.14.7+freethreaded-linux-x86_64-gnu/bin/python3.14t"

child = textwrap.dedent("""
    import sys, time, timeit
    def work():
        total = 0
        for i in range(2_000_000):
            total += (i * i) % 7
        return total
    best = min(timeit.repeat(work, number=1, repeat=7))
    print(sys._is_gil_enabled(), f"{best:.3f}", sys.abiflags or "-")
""")

def run(exe, env_extra=None):
    env = dict(os.environ, **(env_extra or {}))
    gil, best, abi = subprocess.run([exe, "-c", child], capture_output=True, text=True, env=env).stdout.split()
    return gil, float(best), abi

rows = {"3.14 normal build": run(GIL), "3.14t free-threaded": run(FREE), "3.14t with PYTHON_GIL=1": run(FREE, {"PYTHON_GIL": "1"})}
base = rows["3.14 normal build"][1]
print(f"{'build':26}{'GIL on?':>9}{'abi':>5}{'1 thread, best of 7':>22}{'vs normal':>11}")
for name, (gil, best, abi) in rows.items():
    print(f"{name:26}{gil:>9}{abi:>5}{best:>20.3f} s{(best / base - 1) * 100:>+10.0f}%")
output · Python 3.14runs offline
build                       GIL on?  abi   1 thread, best of 7  vs normal
3.14 normal build              True    -               0.125 s        +0%
3.14t free-threaded           False    t               0.140 s       +12%
3.14t with PYTHON_GIL=1        True    t               0.142 s       +14%
# measured on the course machine; your numbers will differ

What you see: the t build reports the GIL as off and has the t ABI flag; setting PYTHON_GIL=1 turns it back on; and the single-thread loop is slower on the free-threaded build by the percentage in the last column for this workload.

Why: without the GIL every reference-count and container operation has to be thread-safe by other means, and that costs a little on each operation.

Normal build

One thread runs at a time.

normal.txtruns offline
python3.14
sys._is_gil_enabled() -> True
fast single thread

Free-threaded

Threads in parallel.

free.txtruns offline
python3.14t
sys._is_gil_enabled() -> False
slower single thread,
parallel CPU-bound threads

The shift: A separate build that trades some single-thread speed and ecosystem readiness for true thread parallelism.

Land it I say free-threading removes the GIL in a separate officially supported build, costs some single-thread speed and needs thread-safe extensions, and I would adopt it only for CPU-bound threaded code after a measured trial of my own dependencies.

Likely follow-ups
"What overhead did the chapter measure elsewhere?"

The chapter's section 05 benchmark gave about 23 percent single-thread overhead on 3.14t. That was for its loop (400,000 orders through CPU-bound rules): 0.70 s on 3.14 and 0.84 s on 3.14t with one thread. The run above this question used a different loop, so its percentage differs.

The overhead comes from the work that replaces the GIL. Reference counts need atomic or biased handling, containers take small locks, and the interpreter is somewhat less able to specialise some instructions. How much of that a loop hits depends on what it does: a loop full of object creation and attribute access pays more than a loop that calls one C function.

Published figures from the CPython project for 3.14 are lower, in the single digits to around 10 percent on common benchmarks, and they change between releases. I would not quote one number as fact.

My statement is: "a measurable cost, which depends on the code, so I measure it on mine."

"What happens if I import a C extension that is not thread-safe?"

The program keeps working, but the GIL comes back. When a free-threaded interpreter imports a compiled extension, it checks a flag that the extension sets to say "I am safe without the GIL". If the flag is missing, the interpreter turns the GIL on for the whole process and prints a warning.

q79_gil_flag.py · Python 3.14 and 3.14truns offline
python3.14                 -> (3, 14) GIL enabled: True
python3.14t                -> (3, 14) GIL enabled: False
PYTHON_GIL=1 python3.14t   -> (3, 14) GIL enabled: True

The third line shows the switch: PYTHON_GIL=1 forces the lock on, and PYTHON_GIL=0 forces it off even for extensions that have not declared support. That last option is at your own risk, since the extension may corrupt data.

The consequence for a team is that one old dependency can quietly cancel the whole benefit. So I check sys._is_gil_enabled() at start-up in the real service and look for cp314t wheels for every dependency.

"Does it help asyncio?"

Not directly. asyncio runs all coroutines on one event loop in one thread. Switching between tasks happens only at await, so it never fought over the GIL in the first place. An async service on 3.14t is about as fast as on 3.14, minus the single-thread overhead.

It helps in three places:

  1. CPU work in threads: asyncio.to_thread sends work to a pool. On a GIL build, CPU-bound work there does not run in parallel; on 3.14t it does.
  2. Several loops: you can run one event loop per thread, each on its own core, which is not useful with a GIL.
  3. Mixed workloads: a service that does some request parsing, some validation, and some waiting can overlap them better.

For a plain I/O-bound API, the usual choice stays: coroutines for many waits, threads for blocking libraries. Removing the GIL does not make a coroutine cheaper than a thread. A coroutine is a small heap object, while a thread reserves its own stack and is scheduled by the operating system.

"What is the difference from sub-interpreters?"

Both give parallel Python, but they solve it in opposite ways. Free-threading removes the lock and keeps one shared world: all threads see the same objects, lists and dicts. Sub-interpreters keep a lock, but give every interpreter its own, and share no Python objects.

That makes the cost different. With free-threading, passing a big structure to another thread costs nothing, since it is the same memory. The price is that you must reason about races. With interpreters, a race on objects cannot happen by construction, but data must be copied or sent through a shareable type, so a large structure is expensive to hand over.

A rough example: a 2 GB lookup table used by 8 workers. With threads on 3.14t, it exists once. With interpreters it would be loaded 8 times, or placed in a shared buffer.

My choice: interpreters when the tasks are independent and I want isolation, and free-threading when many workers must read or update one large in-memory structure.

Q80 · Design. "Your team wants the free-threaded build for a CPU-heavy service. Write the evaluation plan."

Reveal answer

Strong answer I treat it as an experiment with a decision at the end, in six steps. 1. Define success: a throughput or cost target (for example 2.5 times more requests per second per host, or the same load on half the machines), a latency limit (p99 not worse than today) and a memory limit.

2. Check the dependency stack: list every direct and transitive dependency, look for cp314t wheels, and flag the C extensions that do not declare free-threading support. If a critical one forces the GIL back on, the plan stops here. Run the test suite with PYTHON_GIL=0 and look for the re-enable warning.

3. Review thread safety: find shared mutable state (module-level dicts, counters, caches, singletons), check each for a lock or immutability, add locks, and run the tests under a thread-stress harness. Bugs that the GIL hid will show up.

4. Benchmark honestly: the same code and the same real workload on 3.14 (GIL) and 3.14t, in one thread to measure the overhead and in 1, 2, 4, 8 and N threads to measure scaling. Record throughput, p50 and p99 latency, CPU use and peak memory. Compare against the cheap alternatives: a process pool on the normal build, and moving the hot loop to native code.

5. Canary: run one instance on production traffic with a quick rollback, compare error rates, latency and memory for days, and watch for rare race conditions. 6. Decide and record: adopt, delay or reject, with the numbers; set a re-check date, because each release changes the picture.

Picture it The core of step 4 as a small harness, run on both builds.

The setup: A request-like CPU task, served by 1, 4 and 8 worker threads for a fixed number of requests. The harness reports throughput and 99th-percentile latency per request.

q80_eval_harness.py · Python 3.14runs offline
import subprocess, textwrap

U = "/home/iam100god/.local/share/uv/python/"
BUILDS = {"3.14 (GIL)": U + "cpython-3.14.7-linux-x86_64-gnu/bin/python3.14",
          "3.14t (no GIL)": U + "cpython-3.14.7+freethreaded-linux-x86_64-gnu/bin/python3.14t"}

child = textwrap.dedent("""
    import resource, time, sys
    from concurrent.futures import ThreadPoolExecutor

    def handle(_):
        t = time.perf_counter()
        total = 0
        for i in range(400_000):                      # a CPU-bound 'price this order'
            total += (i * i) % 7
        return time.perf_counter() - t

    def bench(workers, requests=48):
        start = time.perf_counter()
        with ThreadPoolExecutor(workers) as pool:
            latencies = sorted(pool.map(handle, range(requests)))
        wall = time.perf_counter() - start
        p99 = latencies[int(0.99 * (len(latencies) - 1))]
        return requests / wall, p99 * 1000

    for workers in (1, 4, 8):
        rps, p99 = bench(workers)
        print(f"{workers} {rps:.0f} {p99:.0f}")
    print("rss", resource.getrusage(resource.RUSAGE_SELF).ru_maxrss // 1024)
""")

print(f"{'build':16}{'threads':>8}{'req/s':>8}{'p99 ms':>9}")
for name, exe in BUILDS.items():
    lines = subprocess.run([exe, "-c", child], capture_output=True, text=True).stdout.splitlines()
    for line in lines[:-1]:
        w, rps, p99 = line.split()
        print(f"{name:16}{w:>8}{rps:>8}{p99:>9}")
    print(f"{'':16}peak RSS {lines[-1].split()[1]} MB")
output · Python 3.14runs offline
build            threads   req/s   p99 ms
3.14 (GIL)             1      39       27
3.14 (GIL)             4      18      307
3.14 (GIL)             8      19      624
                peak RSS 15 MB
3.14t (no GIL)         1      35       37
3.14t (no GIL)         4     137       38
3.14t (no GIL)         8     228       45
                peak RSS 21 MB
# measured on the course machine (12 cores); your numbers will differ

What you see: on the GIL build adding threads does not help at all (throughput even falls, 39 to 18 requests per second) and the per-request p99 grows from 27 ms to 300 to 600 ms, because requests wait for the GIL; on the free-threaded build throughput climbs with threads (35, 137, 228 requests per second) and p99 stays near 40 ms. The RSS lines show the memory cost: 15 MB against 21 MB here.

Why: the harness answers the four questions of the plan with numbers: does it scale, what happens to tail latency, what does it cost in memory, and what is the single-thread cost (the 1-thread row).

Hope

"It should be faster."

hope.txtruns offline
swap python3.14 -> python3.14t
deploy everywhere
check Twitter for bugs

Plan

Gates with numbers.

plan.txtruns offline
1 target  2 dependency scan
3 thread-safety review
4 benchmark 5 canary 6 decide

The shift: Replace a hopeful switch with a gated experiment whose stop conditions are written down in advance.

Land it I write the plan as gates: success numbers first, then a dependency scan, a thread-safety review, an honest benchmark against the cheaper alternatives, a canary with rollback, and a recorded decision with a re-check date.

Likely follow-ups
"What are the stop conditions?"

I write the stop conditions before the trial starts, so the result decides and no one argues afterwards. They are the plan's exits:

  1. Dependency: a critical library has no free-threaded wheel, or turns the GIL back on. Then there is nothing to test.
  2. Cost beats gain: single-thread overhead (say 20 percent) is not paid back by scaling. If four threads give 2 times and the overhead is 20 percent, the net is about 1.7 times, which a process pool may match more simply.
  3. Tail latency: p99 at the target load is worse than today's.
  4. Races: a data-race failure in stress tests that I cannot fix cleanly.
  5. Memory: peak use exceeds the host's budget.

If any one is hit, the result is "not yet", with a re-check date tied to the next Python release. It is a decision, not a failure, and the numbers are recorded so the same question is not reopened without new facts.

"What are the cheaper alternatives I must compare against?"

The free-threaded build has to beat the cheap options, not beat nothing. I compare against four, each tried on the same workload.

First, a process pool on the normal build. It needs no new interpreter, and its costs are memory (each worker holds its own copy) and the pickling of arguments and results.

Second, concurrent.interpreters (3.14), which gives parallelism with isolation. The API is young, and extensions must support it.

Third, moving the hot loop into native code. NumPy, Cython or Rust can often make a loop 10 to 100 times faster, which beats any threading gain, and they release the GIL.

Fourth, the cheapest of all: run more single-threaded processes behind the load balancer. If requests are independent, 4 processes on 4 cores serve about 4 times the traffic with no code change, at the price of memory.

If the free-threaded service is only 10 percent better than that, the extra risk is not worth it.

"How do I find thread-safety problems before production?"

Races are probabilistic, so the search has to be both a code review and a stress test.

  1. Find the shared state: search for module-level dicts, lists and counters, class attributes that are mutated, caches, singletons and lazily created clients. Each gets an owner: a lock, an immutable value, or one thread.
  2. Run tests with many threads: repeat the test suite 100 times with 8 or more threads. Failures that appear only some of the time are the race signal.
  3. Stress each structure: a small test that hammers one cache from 16 threads for a minute and asserts an invariant, such as "size equals the number of successful inserts".
  4. Use tooling: faulthandler to dump stacks on a hang, and a ThreadSanitizer build of CPython where available, since it finds races directly.

I run these for minutes, not milliseconds. A test that passes once says little.

"What do I tell management if the numbers are good?"

I translate the benchmark into a cost, because that is what a manager decides on. For example: "the same traffic fits on 6 hosts instead of 10" or "each host handles 40 percent more requests". I also state the precise condition: measured on our workload, with our dependencies, at a given p99.

Then I list what stays risky. Extension support can change when we upgrade a library. Rare races may appear only in production. The build is separate, so it needs its own images and its own monitoring.

Third, the rollback: we can switch the canary back to the normal build in minutes, because the code is the same.

Fourth, the next review: the 3.15 release and the free-threaded wheel list for our dependencies.

If the numbers are bad, I report that just as plainly: "no gain over processes; do not proceed", with the figures attached, so the question is not reopened without new facts.

10 · DrillDrill: Concurrency, Performance and Memory — Q81–Q115

These thirty-five questions cover what interviewers ask once you say "I know asyncio": how the event loop really works, how to choose between threads, processes, interpreters and free-threading, and how to find and fix slowness with numbers. Every answer is short enough to say aloud; the picture underneath it was produced by running the code. Say your answer first, then reveal.

Drill · asyncio

These questions test whether you can explain the event loop as one thread with a ready queue, and whether you know the five ways async code goes wrong in production: blocking calls, lost tasks, swallowed cancellation, unbounded concurrency and leaked context.

Q81. "How does the asyncio event loop work, one level down?"

Reveal answer

Strong answer The event loop is a single thread running one big while loop. It keeps three things: a ready queue of callbacks that can run right now, a heap of timers for callbacks scheduled for later, and a selector (on Linux, epoll) that the operating system uses to say "this socket is now readable".

One turn of the loop does four things in order. It works out how long it may sleep: zero if the ready queue is not empty, otherwise until the next timer is due. It asks the selector which sockets are ready, waiting at most that long. It moves finished I/O and due timers into the ready queue. Then it runs every callback that was in the queue at that moment, one after another, each to completion.

A Task is just a callback that keeps pushing a coroutine forward. Each push is one call to coro.send(None). The coroutine runs until it hits an await on something not ready yet. That something is a Future. The task registers itself as the future's "wake me" callback and returns to the loop, which is now free to run other tasks.

So await is not magic and not a thread. It means "I cannot continue until this future is done; run someone else meanwhile". Everything is cooperative: a task is only ever paused where you wrote await.

Picture it Two tasks and one plain callback, to watch the order the loop runs them in.

The setup: Task T1 and task T2 each print a line, then give control back with await asyncio.sleep(0). A call_soon callback is queued first.

loop_order.py · Python 3.14runs offline
import asyncio

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

async def main():
    loop = asyncio.get_running_loop()
    loop.call_soon(print, "  callback A (call_soon)")
    t1 = asyncio.create_task(worker("T1", 2))
    t2 = asyncio.create_task(worker("T2", 2))
    print("main: tasks created, now awaiting")
    await asyncio.gather(t1, t2)

asyncio.run(main())

Make the invisible visible: Run it and read the order of the lines. Nothing runs in parallel; the loop alternates.

output · Python 3.14runs offline
main: tasks created, now awaiting
  callback A (call_soon)
  T1 step 0
  T2 step 0
  T1 step 1
  T2 step 1

What you see: The callback ran before either task started, because it was already in the ready queue when the tasks were created. Then T1 and T2 take strict turns: each runs up to its await, goes to the back of the queue, and lets the other run.

one loop turn, in pseudocoderuns offline
# illustrative
timeout = 0 if ready else time_until(next_timer)
events  = selector.select(timeout)      # epoll_wait(...)
for key in events: ready.append(callback_for(key))
while timers and timers[0].when <= now: ready.append(timers.pop())
for handle in list(ready):              # run what is queued NOW
    ready.popleft().run()               # each runs until it returns

Why: A callback that never returns (a long loop, a time.sleep, a blocking socket read) stops the whole turn. No other task, timer or socket is looked at until it returns. That is the root of every "asyncio is mysteriously slow" incident (Q82).

Land it I explain asyncio as one thread, a ready queue, a timer heap and an epoll selector, where await means "park me on this future and run someone else" and nothing can interrupt a task between awaits.

Likely follow-ups
"What is the selector actually doing?"

The selector is a thin wrapper over the operating system's "which sockets have news" call. On Linux that is epoll, on macOS and the BSDs it is kqueue, and elsewhere it falls back to select. On Windows the default loop uses a different mechanism, IOCP, where the system finishes the read and reports it.

The loop registers each open socket once with a flag: tell me when it is readable, or writable. Then each turn it makes one epoll_wait call with a timeout. The kernel keeps the list of watched sockets, so the cost does not grow with the number of idle ones. It can watch tens of thousands and return only the few that are ready.

The timeout is where timers come in. If the next timer is due in 30 ms, the loop waits at most 30 ms. If the ready queue is not empty, it waits 0.

That is the whole reason one thread can serve many connections: it sleeps in one place, and wakes only when something can be done.

"Where do asyncio.sleep(0.5) and call_later live?"

They live in a min-heap, a structure where the smallest item is always on top. Each timer is stored with its due time, so the next one to fire is found in constant time and inserted in logarithmic time.

The path of await asyncio.sleep(0.5) has four steps:

  1. Create: sleep makes a Future and calls loop.call_later(0.5, future.set_result, None).
  2. Park: the task awaits the future and returns control to the loop.
  3. Wait: the loop computes its sleep time from the top of the heap and calls epoll_wait for at most that long.
  4. Wake: when the time has passed, the timer callback runs, sets the result, and the task is put on the ready queue.

The practical consequence is that timers are only as precise as the loop is free. If one callback holds the loop for 400 ms, every timer due in that window fires about 400 ms late. A sleep(0.5) can then take 0.9 s, which is how loop lag shows up in real services.

"What does await asyncio.sleep(0) do?"

It yields control once and does nothing else. The task is put at the back of the ready queue, the loop runs everyone who is already waiting there, and then the task continues. No timer is created and no I/O is involved.

The demo above uses it to make the alternation of two tasks visible: each prints a line, yields, and the other gets a turn.

In real code it is a cheap way to break up a long CPU loop. A loop of 1,000,000 steps that calls await asyncio.sleep(0) every 10,000 steps lets heartbeats and other requests run 100 times during the work, instead of freezing them for the whole duration.

It is a bandage, though. The loop is still one thread, so total throughput does not improve and the yielding itself costs time. If the work is heavy, I move it to a process pool and await the result. I use sleep(0) for light work that is only slightly too long, such as processing a large list in slices.

"Is uvloop a different model?"

No. uvloop is a faster implementation of the same loop, built on libuv, the C library that powers Node.js. The model is unchanged: one thread, a ready queue, timers, coroutines, tasks and futures. Your code does not change; you install it and set it as the loop policy or use the runner option.

It speeds up the plumbing: accepting sockets, reading and writing, and scheduling callbacks. Reports from its authors and users show that gain on services that handle very many small requests, where the loop itself is a large share of the time. I would not quote a figure without measuring.

It does not help in three cases. A blocking call still blocks it. CPU-bound work still blocks it. And if the profile shows time inside your handlers or the database, the loop was never the problem. It also does not run on Windows.

My approach: profile first, and adopt it only if the loop shows up as the cost.

Q82 · Scenario. "p99 latency jumped from 40 ms to 2 s after someone added one call inside an async handler. Diagnose."

Reveal answer

Strong answer That pattern, every request slow and the tail exploding, usually means someone put a blocking call inside async def. A requests.get, a synchronous database driver, time.sleep, a big json.loads, a CPU loop. While it runs, the event loop cannot run anything else, so all in-flight requests wait in line behind it.

The arithmetic fits: 40 requests arriving together, each blocking the loop for 50 ms, finish after 40 x 50 ms = 2.0 s. The call itself is only 50 ms, but the 40th request waits for 39 others.

To confirm, I turn on asyncio debug mode, which logs any callback that holds the loop longer than slow_callback_duration. In production I would take a py-spy dump of the process and see the main thread sitting in the blocking call, and I would graph event loop lag: schedule a call_later(0.1) repeatedly and record how late it fires.

The fix is to keep the loop free: use an async client (httpx.AsyncClient, an async driver), or push the blocking call to a worker thread with await asyncio.to_thread(...).

Picture it Forty simulated requests, each doing 50 ms of "work" three different ways. Only one line of the handler changes.

The setup: Three handlers: an async sleep, a blocking time.sleep in async code, and the blocking call moved to a thread.

blocking_in_async.py · Python 3.14runs offline
import asyncio, time

async def handler_ok():
    await asyncio.sleep(0.05)

async def handler_blocking():
    time.sleep(0.05)               # ❌ TRAP: blocks the whole loop

async def handler_thread():
    await asyncio.to_thread(time.sleep, 0.05)   # ✅

async def one(h, started):
    await h()

Make the invisible visible: Measured latency of 40 concurrent requests for each handler.

output · Python 3.14runs offline
handler_ok        median     51 ms   slowest     51 ms
handler_blocking  median   1056 ms   slowest   2013 ms
handler_thread    median    104 ms   slowest    155 ms
# measured on the course machine (12 cores); your numbers will differ

What you see: The awaiting handler answers everyone in about 50 ms. The blocking one shows a median of about a second and a slowest of 2 s, exactly 40 x 50 ms. The thread version is slightly slower per request (thread hand-off) but still flat.

Make the invisible visible: Debug mode names the culprit while a heartbeat task tries to keep ticking.

slow_callback.py output · Python 3.14runs offline
  heartbeat
Executing <Task finished name='Task-3' coro=<bad_handler() done, defined at /home/iam100god/Desktop/AI_COURSE/code/e19-python-deep-dive/E/slow_callback.py:8> result=None created at /home/iam100god/.local/share/uv/python/cpython-3.14.7-linux-x86_64-gnu/lib/python3.14/asyncio/tasks.py:735> took 0.401 seconds
  heartbeat
  heartbeat

Blocking call in the handler

The loop is frozen for 50 ms per request.

slow.pyruns offline
async def handler():
    data = requests.get(URL)  # blocks
    return data.json()

Await an async client

The loop serves others while waiting.

fast.pyruns offline
async def handler():
    r = await client.get(URL)
    return r.json()

The shift: A handler may wait, but it must wait with await, never with a blocking call.

Why: The heartbeat should have fired every 50 ms. The log line says one task held the loop for 0.400 s, and names the coroutine, bad_handler, and the line where it was created.

Land it I say that one blocking call in an async handler serialises every request on the loop, I prove it with debug-mode slow-callback logs and loop-lag, and I fix it by awaiting an async client or moving the call to a thread.

Likely follow-ups
"How would you catch this before production?"

I use three guards, each cheap, each catching the problem at a different stage.

  1. Debug mode in tests: run with PYTHONASYNCIODEBUG=1 or asyncio.run(main(), debug=True). The loop then logs any callback that holds it longer than slow_callback_duration (0.1 s by default), and names the culprit.
  2. A concurrent load test: fire 50 requests at once against the test environment and fail the build if p99 is more than a few times the median. A blocking call shows up as a staircase of latencies, since the n-th request waits for n-1 others.
  3. A linter: Ruff has ASYNC rules that flag time.sleep, requests.get and blocking file calls inside async def.

The linter is the cheapest and catches the most common cases before the code is even run. The load test is the one that catches what the linter cannot see, such as a blocking call hidden inside a helper library.

"How big is the thread pool behind to_thread?"

The default executor is a ThreadPoolExecutor whose size is min(32, cpu_count + 4). On this 12-core machine that is 16 threads. A single-core container gets 5, and the cap is 32.

Work it out for a slow call. Suppose each blocking call takes 200 ms and 100 requests arrive together. With 16 threads they run in waves of 16, so the last wave starts after 6 waves: 7 waves in total, about 1.4 s for the last request. With 100 threads it would be 0.2 s, but 100 threads cost memory and compete for other resources.

pool arithmeticruns offline
waves = ceil(100 / 16) = 7
last request waits about 7 x 200 ms = 1.4 s

For a heavy blocking workload I create my own executor with a chosen size and use loop.run_in_executor(my_pool, ...). That also keeps it from starving other code that uses the default pool, such as DNS lookups.

"Why does the p99 explode while the average only doubles?"

Because the delay is queueing, and queueing is lopsided. The first request in a burst waits for nothing. The last waits for every one before it. The average sits in the middle, and the 99th percentile is near the worst.

Use the incident's own numbers. Forty requests arrive together, each blocking the loop for 50 ms. Request 1 finishes after 50 ms, request 20 after 1.0 s, request 40 after 2.0 s. The mean is about 1.0 s, the p99 is about 2.0 s.

In practice the mean is lower, because requests do not all arrive in one instant. A busy service sees a mix of quiet moments and bursts. Quiet moments pull the mean down, while a burst still creates a tail, so p99 jumps while the mean only doubles.

That is why I watch p99 and event-loop lag, and not the mean. The mean hides the user who waited behind the whole burst, and that user is the one who files the complaint.

"Is moving the call to a thread always safe?"

Only if the code is thread-safe. Moving a call to a worker thread means it can now run at the same time as other code on the loop thread, and at the same time as itself in other threads.

Two examples of what breaks. A client library that keeps a global session or a shared connection may corrupt it when two threads use it together. An object created in one request and shared with another can be modified from two threads. Neither failed before, because everything ran one step at a time on the loop.

The second limit is the one in the chapter: a thread gives overlap for waiting, not parallel CPU. On a normal build, if the call computes for 50 ms, it holds the GIL and competes with the loop thread for it. For CPU-heavy work I use a process pool (Q93).

My checklist before moving a call: is the library documented as thread-safe, does it share state, and is the call waiting or computing?

Q83. "Coroutine versus Task versus Future."

Reveal answer

Strong answer A coroutine object is what you get by calling an async def function. Calling it does not run the body. It gives you a paused recipe that only moves when somebody drives it, for example with await.

A Future is a placeholder for a result that does not exist yet. It has set_result, set_exception, cancel and done-callbacks. Nothing runs inside it. Somebody else, such as a callback or the loop's I/O code, fills it in later.

A Task is a Future that drives a coroutine. asyncio.create_task(coro) wraps the coroutine and schedules it on the loop right away, so it starts running at the next loop turn even if you never await it. When the coroutine returns, the task's result is set.

The rule of thumb: await a coroutine to run it inline, one after another; wrap it in a Task to run it concurrently; and treat Future as a low-level tool you rarely create by hand.

Picture it The three objects side by side, plus the classic mistake of forgetting to await.

The setup: One coroutine function price. We call it directly, wrap it in a task, build a bare future, and finally call it without awaiting.

coro_task_future.py · Python 3.14runs offline
import asyncio, warnings

async def price(n):
    print(f"  price({n}) body is running")
    await asyncio.sleep(0.01)
    return n * 2

async def main():
    c = price(1)
    print("1. coroutine object:", type(c).__name__, "- body has NOT run yet")
    print("   result of awaiting it:", await c)

    t = asyncio.create_task(price(2))
    print("2. task:", type(t).__name__, "- scheduled; done?", t.done())
    await asyncio.sleep(0)
    print("   after one loop turn the body started; done?", t.done())
    print("   result:", await t)

    fut = asyncio.get_running_loop().create_future()
    print("3. future:", type(fut).__name__, "- nobody is running anything for it")
    asyncio.get_running_loop().call_later(0.01, fut.set_result, "set by callback")
    print("   result:", await fut)
    print("4. Task is a Future subclass:", issubclass(asyncio.Task, asyncio.Future))

Make the invisible visible: What each object is, and when the body of price actually ran.

output · Python 3.14runs offline
1. coroutine object: coroutine - body has NOT run yet
  price(1) body is running
   result of awaiting it: 2
2. task: Task - scheduled; done? False
  price(2) body is running
   after one loop turn the body started; done? False
   result: 4
3. future: Future - nobody is running anything for it
   result: set by callback
4. Task is a Future subclass: True
--- forgetting to await ---
/home/iam100god/Desktop/AI_COURSE/code/e19-python-deep-dive/E/coro_task_future.py:28: RuntimeWarning: coroutine 'price' was never awaited
  price(9)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

What you see: Item 1: the body had not run when the coroutine object existed. Item 2: the task was already scheduled (done? False), and its body started on the next loop turn. Item 3: a bare future waits for someone to call set_result. Item 4: Task is a subclass of Future. The last lines show the warning Python prints when you call a coroutine function and drop the result.

Why: The warning "coroutine was never awaited" is almost always a missing await: the function was called, a coroutine object was created, and nothing ever drove it.

Land it I say a coroutine is a paused recipe, a Future is an empty result slot, and a Task is a Future that runs a coroutine on the loop, which is why create_task starts work and a bare call does not.

Likely follow-ups
"When do I use await coro() versus create_task(coro())?"

The rule is about whether the next line needs the answer. Use await when it does. Use create_task when the work can proceed meanwhile, and you will collect the answer later.

The arithmetic shows the gain. Take two calls of 300 ms and 500 ms:

timingruns offline
await a(); await b()      -> 300 + 500 = 800 ms   (one after the other)
t = create_task(a()); await b(); await t
                          -> max(300, 500) = 500 ms (overlapping)

That is the whole speed-up asyncio offers for waiting work. It does not make any single call faster; it removes idle gaps between calls.

One trap: writing await create_task(a()) on one line gives no overlap, since you wait for it at once. The overlap comes from starting several tasks before awaiting any of them. For a batch, I use a TaskGroup so I cannot forget to collect them.

"What is ensure_future and should I use it?"

It is the older way to turn something awaitable into a Task or Future, and it accepts several inputs: a coroutine becomes a task, a Future is returned unchanged, and an awaitable object is wrapped. It was the main tool before create_task was added in 3.7.

The problem is its flexibility. Because it accepts several kinds of input, the reader cannot tell from the call what it will do. The documentation now recommends asyncio.create_task for coroutines.

In new code I use two tools only:

  1. TaskGroup: when a block of code owns the children. It handles waiting, failure and cancellation for me.
  2. create_task: for a single background task, where I keep a reference and add a done-callback (Q86).

I read ensure_future in old code and in some library code that must accept both kinds of input. When I meet it I replace it if the argument is always a coroutine, and I leave it where it is the library's contract.

"What does asyncio.run do with the first coroutine?"

It does five things, in this order. It creates a new event loop. It wraps the coroutine in a Task. It runs the loop until that task finishes. It cancels any tasks that are still pending and lets them finish their clean-up. Then it closes the loop and returns the result or raises the exception.

That order explains two rules. First, you call it once, at the top of the program. It makes a loop and tears it down, so calling it again and again creates and destroys loops, which is slow and breaks anything tied to the old loop.

Second, it must not be called from inside a running loop. The demo in Q88 shows the error: asyncio.run() cannot be called from a running event loop. In Jupyter you just use await because a loop is already running.

The clean-up step is a quiet benefit. Background tasks you forgot are cancelled when main ends. If they matter, you should have awaited them earlier.

"Can I await the same Task twice?"

Yes. A Task is like a Future: when the coroutine finishes, the result is stored on the task, and each await t returns it at once. If the coroutine raised an exception, each await raises that same exception. So several callers can wait for one piece of work, and it runs only once.

A bare coroutine is different. It is a one-shot recipe. Once awaited, it is spent, and a second await fails.

q83_reuse.py · Python 3.14runs offline
42
coroutine twice: cannot reuse already awaited coroutine
task twice: 42 42

This matters for caching. If three request handlers need the same slow lookup, I store the Task in a dict (not the coroutine) and let each one await it. The first request starts the work and the others share it, which avoids three calls to the downstream service.

Q84. "gather versus TaskGroup — what changes when one task fails?"

Reveal answer

Strong answer gather and TaskGroup both run several awaitables together. They differ in what they do when one fails.

With gather (default settings), the first exception is raised to the caller, but the sibling tasks keep running in the background. Nobody is told they are orphaned. They may finish later, hold connections, or fail with no one watching.

With asyncio.TaskGroup (3.11+), the first failure cancels all siblings, the async with block waits until every child has actually stopped, and then raises an ExceptionGroup holding every error. Nothing outlives the block. That is called structured concurrency: the lifetime of tasks is tied to a block of code.

So for new code I default to TaskGroup. I keep gather for the case where I want every result, including failures, and use return_exceptions=True on purpose.

Picture it One task fails after 50 ms; a sibling would take 200 ms. What happens to the sibling?

The setup: boom() raises ValueError at 50 ms. ok("slow") prints when it finishes or when it is cancelled.

gather_vs_taskgroup.py · Python 3.14runs offline
import asyncio

async def ok(name, delay):
    try:
        await asyncio.sleep(delay)
        print(f"  {name}: finished")
    except asyncio.CancelledError:
        print(f"  {name}: cancelled")
        raise

async def boom():
    await asyncio.sleep(0.05)
    raise ValueError("price service down")

async def with_gather():
    print("gather:")
    try:
        await asyncio.gather(boom(), ok("slow", 0.2))
    except ValueError as e:
        print("  caller got:", e)
    await asyncio.sleep(0.3)       # siblings keep running
    print("  (0.3 s later)")

async def with_taskgroup():
    print("TaskGroup:")
    try:
        async with asyncio.TaskGroup() as tg:
            tg.create_task(boom())
            tg.create_task(ok("slow", 0.2))
    except* ValueError as eg:
        print("  caller got:", eg.exceptions)

asyncio.run(with_gather())
asyncio.run(with_taskgroup())

Make the invisible visible: Run both versions.

output · Python 3.14runs offline
gather:
  caller got: price service down
  slow: finished
  (0.3 s later)
TaskGroup:
  slow: cancelled
  caller got: (ValueError('price service down'),)

What you see: Under gather the caller got the error right away, but the sibling "slow" printed finished afterwards: it was never stopped. Under TaskGroup the sibling printed cancelled and the error arrived wrapped in an exception group (note the tuple in the output).

gather: first error, siblings run on

The caller hears about one failure only.

gather.pyruns offline
try:
    await asyncio.gather(a(), b())
except ValueError:
    ...   # b() may still run

TaskGroup: owner of its children

Siblings are cancelled and all errors reported.

group.pyruns offline
try:
    async with asyncio.TaskGroup() as tg:
        tg.create_task(a())
        tg.create_task(b())
except* ValueError:
    ...

The shift: gather reports and walks away; a TaskGroup cleans up before it reports.

Why: gather reports the first failure and walks away. TaskGroup owns its children: it cancels them, waits for them and only then reports. For a service this is the difference between a request that cleans up and one that leaves work running after the client has gone.

Land it I choose TaskGroup because a failed child cancels its siblings and nothing outlives the block, and I use gather only when I explicitly want every result including errors.

Likely follow-ups
"What does gather(..., return_exceptions=True) do?"

It changes what you get back from a failure. Without it, the first exception is raised to the caller (with the default settings) and the other results are lost. With it, every child's outcome is returned in the result list in input order, including exceptions, and nothing is raised for them.

That suits "show whichever of these 10 prices came back". The caller does the sorting:

  1. Run: results = await asyncio.gather(*calls, return_exceptions=True).
  2. Check each item: isinstance(r, BaseException) is true for failures and for a cancelled child. Log them with the input that failed.
  3. Use the rest: keep the successful values.

The danger is the forgotten check. An exception object is an ordinary value in the list, and code that formats or sums it may fail later and far away, or print the error text as if it were data.

I use it only when partial results are acceptable and I handle every item explicitly.

"What if two tasks fail at once in a TaskGroup?"

You get one ExceptionGroup that holds both. The group is raised after all children have stopped, so you see the complete picture instead of just the first error.

The catch is how you handle it. A plain except ValueError does not match, because the exception being raised is a group, not a ValueError. The demo below shows both clauses. The two children failed at nearly the same time, and the group holds both errors:

q84_two_fail.py · Python 3.14runs offline
plain except did not match; got ExceptionGroup
except* ValueError: ['bad price']
except* KeyError  : ["KeyError('missing tenant')"]

Each except* clause gets only the matching members, and both ran for one raise. This surprises people moving from gather, where only the first error arrived. I also remember that one try statement cannot mix except and except*.

"How do I get partial results from a TaskGroup?"

By keeping the Task objects. t1 = tg.create_task(...) returns the task, and after the block ends you can ask each finished task for its result. A task that was cancelled or failed raises when you call result(), so check t1.done() and t1.cancelled() first.

That gives you the results of children that completed before the failure, but not those that were cancelled. If you want every item to run to the end whatever the others do, the group's default is the wrong tool. Instead, I catch the expected errors inside each child and return a small result object:

  1. Wrap: each child runs try: value = await fetch(x) and catches the errors it expects.
  2. Return: a result that carries either a value or an error message.
  3. Cancel on the unexpected: anything else still escapes, cancels the siblings and ends the group.

This keeps the safety property: bugs stop everything, normal failures are data.

"What happens when the code around the group is cancelled?"

The group is cancelled as a whole and nothing is abandoned. When the parent task is cancelled while it sits in async with TaskGroup(), the group cancels every child, waits until each has really stopped (including their finally blocks), and then lets the cancellation continue upward.

The same holds for a timeout around it. async with asyncio.timeout(2): async with TaskGroup() as tg: ... cancels the children after 2 seconds, waits for them, and then raises TimeoutError for the whole block.

The ordering is important for requests. Suppose a handler fans out to 5 services with a 2 s deadline. After 2 s all 5 calls are cancelled and their connections are released. With bare tasks, those 5 calls would keep running for as long as they like, holding connections and costing money.

That is the deadline-without-leaks property. I would also mention that children must let CancelledError pass (Q85), or the group waits for them forever.

Q85. "How does cancellation work, and why must you never swallow CancelledError?"

Reveal answer

Strong answer task.cancel() does not kill the task. It asks the loop to throw a CancelledError into the coroutine at its next await. The coroutine can run finally blocks and clean up, and if it lets the exception propagate, the task ends in the cancelled state.

CancelledError is a subclass of BaseException (since 3.8), not Exception, precisely so that a normal except Exception does not catch it by accident.

If you catch it and carry on, the cancellation is lost. The caller thinks the task is stopping, but it keeps running. Timeouts, TaskGroup, client disconnects and shutdown all depend on cancellation being obeyed, so a swallowed cancel turns into hung requests and processes that will not exit.

The rule: catch CancelledError only to clean up, then re-raise. Put clean-up in finally where possible.

Picture it Two workers that loop forever. One re-raises the cancel, one swallows it.

The setup: Both loop on await asyncio.sleep(0.05). After 0.12 s we call cancel() and wait 0.3 s.

cancel_swallow.py · Python 3.14runs offline
import asyncio

async def bad_worker():
    while True:
        try:
            await asyncio.sleep(0.05)
        except asyncio.CancelledError:
            print("  bad: swallowed cancel, carrying on")   # ❌ TRAP

async def good_worker():
    try:
        while True:
            await asyncio.sleep(0.05)
    except asyncio.CancelledError:
        print("  good: cleaning up, re-raising")
        raise                                              # ✅

async def stop(coro, label):
    t = asyncio.create_task(coro)
    await asyncio.sleep(0.12)
    t.cancel()
    await asyncio.sleep(0.3)               # give it time to obey
    print(f"{label}: 0.3 s after cancel(): done={t.done()} cancelled={t.cancelled()}")

async def main():
    await stop(good_worker(), "good")
    await stop(bad_worker(), "bad ")
    # timeout() is built on cancellation
    try:
        async with asyncio.timeout(0.1):
            await asyncio.sleep(5)
    except TimeoutError:
        print("asyncio.timeout fired -> TimeoutError after cancelling the body")

Make the invisible visible: Did each worker actually stop?

output · Python 3.14runs offline
  good: cleaning up, re-raising
good: 0.3 s after cancel(): done=True cancelled=True
  bad: swallowed cancel, carrying on
bad : 0.3 s after cancel(): done=False cancelled=False
asyncio.timeout fired -> TimeoutError after cancelling the body
(forcing exit: the bad worker is immortal)

What you see: The good worker printed its clean-up line, re-raised, and ended as cancelled=True. The bad worker printed "swallowed cancel" and was still running 0.3 s later (done=False). The last lines show asyncio.timeout firing correctly: it works by cancelling the body, then turning that into TimeoutError.

Swallowing the cancel

The task refuses to stop.

bad.pyruns offline
try:
    await work()
except asyncio.CancelledError:
    log.info("ignoring")  # lost

Clean up, then re-raise

The cancellation completes.

good.pyruns offline
try:
    await work()
except asyncio.CancelledError:
    await cleanup()
    raise

The shift: Cancellation is a request the task must pass on, not a signal it may consume.

Why: asyncio.timeout, wait_for and TaskGroup are all built on cancel(). A coroutine that ignores it breaks all of them at once.

Land it I treat CancelledError as the stop signal for every async feature, so I clean up in finally, re-raise it, and never write a bare except that eats it.

Likely follow-ups
"What if my clean-up code needs to await something?"

Cancellation arrives once, as an exception thrown at the current await, so awaiting in a finally block works in the normal case. The task is not blocked from awaiting just because it has been cancelled.

The risk is a second cancel during the clean-up. If something cancels the task again, for example a shutdown that cancels everything twice, or a timeout that fires while the clean-up runs, the new CancelledError lands in the clean-up await and interrupts it. A database rollback or a lock release might be left half done.

For clean-up that must complete, I protect it:

  1. Keep it short: only the essential step, such as releasing a lease or rolling back.
  2. Shield it: await asyncio.shield(cleanup()) keeps the inner work running if the outer await is cancelled again.
  3. Put a timeout on it: a clean-up that waits on a dead server forever turns a stop request into a hang.

I would rather make clean-up synchronous or fast than clever.

"What does asyncio.shield do?"

Shield protects the inner work from the outer cancellation. When the task that awaits asyncio.shield(coro) is cancelled, the caller sees CancelledError, but the shielded coroutine, which now runs as its own task, carries on to the end.

Here is a scenario. A request handler is writing a payment record. The client disconnects, which cancels the handler. Without shield, the write stops halfway and the database transaction is rolled back, while the payment provider has already taken the money. With await asyncio.shield(save_payment()), the write finishes even though the handler is gone.

The costs are two:

  1. You own the inner task: keep a reference to it and make sure someone eventually awaits it, or its error vanishes (Q86).
  2. It can outlive its owner: at shutdown it may still be running.

I use shield for finishing a commit or an external call that must not be left half done, and never to ignore a shutdown.

"wait_for or asyncio.timeout?"

Both enforce a deadline, but they differ in scope. asyncio.wait_for(coro, 3) wraps one awaitable and cancels it when the 3 seconds run out. async with asyncio.timeout(3): (3.11 and later) covers a whole block, whatever awaits happen inside.

A request usually has one deadline for several steps: authenticate, read the database, call a service, render. With wait_for on each step you must work out the remaining time by hand, and three steps of 3 s each allow 9 s in total. With one timeout(3) around the handler, the whole thing is bounded at 3 s.

The context manager also composes. Timeouts can nest, and the earliest deadline wins, so a helper that adds its own 10 s limit inside a caller's 3 s block still ends at 3 s. The deadline can be moved with reschedule too.

Both raise TimeoutError to the caller, and both rely on the work respecting cancellation.

"How do I stop a task that is stuck in CPU or a blocking call?"

You cannot, and that is the honest answer. Cancellation takes effect only at an await, because that is the only point where the loop gets control. A coroutine inside a 10-second pure-Python loop, or inside time.sleep(10), does not see the request until it comes back.

Threads are the same: Python has no safe way to kill a thread from outside. A thread running in to_thread continues even when the task that started it is cancelled. The awaiting side stops waiting, but the work keeps running.

There are three practical designs:

  1. Cooperative checks: the work loop checks a flag or an Event between chunks, say every 100 ms of work, and returns early.
  2. A process: run it in a child process that you can terminate, accepting the lost state.
  3. Timeouts inside the call: give the library call its own timeout, such as a socket or query timeout.

I design stoppable work from the start, since retrofitting it is hard.

Q86 · Scenario. "Background tasks started with create_task sometimes vanish without finishing. Why?"

Reveal answer

Strong answer The event loop keeps only a weak reference to the tasks it runs. A weak reference does not keep an object alive. If your code does not hold a normal (strong) reference to the task, and nothing else points at it, the garbage collector is free to destroy it, even in the middle of its work.

Typical shape: asyncio.create_task(send_email(order)) inside a handler, result thrown away. Usually it works, because something else happens to reference the task. Under some timing, or once the task is waiting on something only it holds, a garbage-collection pass removes it. The symptom is Python's message "Task was destroyed but it is pending!" or, worse, no message and a missing email.

The fix is to keep a strong reference until the task is done. Either hold tasks in a set and remove them with a done-callback, or, better, run them inside a TaskGroup so a block of code owns them.

A second reason tasks "vanish" is a different bug: an exception raised in a task nobody awaits is only reported when the task object is collected. Always give background tasks a done-callback that logs failures.

Picture it A task that waits on a future only it knows about, started with and without a saved reference.

The setup: The task awaits a private future. We drop our own variable, run one normal garbage-collection pass, and count the tasks the loop can still see.

task_vanish.py · Python 3.14runs offline
import asyncio, gc

async def waits_on_something_nobody_else_holds():
    fut = asyncio.get_running_loop().create_future()   # only this task knows the future
    await fut
    print("  finished (you will not see this)")

async def run(keep):
    background = []
    t = asyncio.create_task(waits_on_something_nobody_else_holds())
    if keep:
        background.append(t)           # ✅ strong reference
    del t
    await asyncio.sleep(0)             # let the task start and park on its future
    gc.collect()                       # a normal GC pass, as happens at any time
    await asyncio.sleep(0.05)
    print(f"  keep reference={keep}: tasks the loop still sees = "
          f"{len([x for x in asyncio.all_tasks() if x is not asyncio.current_task()])}")

for keep in (False, True):
    asyncio.run(run(keep))

Make the invisible visible: Run it. The first case loses the task; the second keeps it.

output · Python 3.14runs offline
Task was destroyed but it is pending!
task: <Task pending name='Task-2' coro=<waits_on_something_nobody_else_holds() done, defined at /home/iam100god/Desktop/AI_COURSE/code/e19-python-deep-dive/E/task_vanish.py:3> wait_for=<Future pending cb=[Task.task_wakeup()]>>
  keep reference=False: tasks the loop still sees = 0
  keep reference=True: tasks the loop still sees = 1

What you see: Without a reference the task was destroyed while pending: Python printed "Task was destroyed but it is pending!" and the loop saw 0 tasks. With a reference in a list the loop still saw 1 task.

The fix: the documented pattern, a set plus add_done_callback(discard), or a TaskGroup.

keep_refs.py · Python 3.14runs offline

background = set()
def spawn(coro):
    t = asyncio.create_task(coro)
    background.add(t)                      # strong reference
    t.add_done_callback(background.discard)
    return t

async def safe():
    spawn(job("safe-set"))
    gc.collect()
    await asyncio.sleep(0.2)

async def structured():
    async with asyncio.TaskGroup() as tg:
        tg.create_task(job("taskgroup"))
        gc.collect()

for f in (unsafe, safe, structured):
    print(f.__name__ + ":")
    asyncio.run(f())

Fire and forget

Nothing holds the task.

lost.pyruns offline
asyncio.create_task(send_email(o))
# result discarded

Keep a reference

A set owns the task until it is done.

kept.pyruns offline
t = asyncio.create_task(send_email(o))
bg.add(t)
t.add_done_callback(bg.discard)

The shift: A task needs an owner; the loop only watches it weakly.

Why: In my first script (task_refs.py), a task that was sleeping on a timer survived gc.collect() even without a reference, because the timer held it. So the bug does not always reproduce: it depends on what else points at the task. That is exactly why it hides in production and why the rule is "always keep the reference".

Land it I never fire and forget a bare create_task; I keep tasks in a set with a done-callback or run them in a TaskGroup, because the loop only holds them weakly and unretrieved exceptions disappear silently.

Likely follow-ups
"Why does the loop use weak references at all?"

To avoid a leak. If the loop held a strong reference to every task, a task waiting on a future that nobody will ever complete would stay in memory forever, along with everything it references. A service that starts thousands of such tasks per hour would grow without limit.

With a weak reference, the loop says "I will run this task while something else keeps it alive". A task whose result nobody wants is then freed, which is the right result for most abandoned work.

The cost is that you, the programmer, own the lifetime of any task that must finish. The asyncio documentation says this directly and recommends saving a reference to the task returned by create_task.

The bug is rare and timing-dependent. Most of the time something else references the task (an object waiting on it, a stack frame), so the code seems fine in tests. Then a garbage-collection pass runs at the wrong moment in production. I treat a bare create_task(...) statement as a code-review defect, in the same way as an ignored return value of a function that can fail.

"How do I make sure failures in background tasks are not lost?"

I add a done-callback that reads the outcome. A task that fails with nobody waiting for it reports only "Task exception was never retrieved", and only when the task object is collected, which can be long after the failure. In a service that log line may never be seen.

  1. Keep the task: tasks.add(t) in a set owned by the app.
  2. Add the callback: t.add_done_callback(on_done), where on_done removes the task from the set.
  3. Read the result there: inside it, check t.cancelled(), then call t.exception() and log it with a stack trace and the job's identity.

In the earlier demo (silent_worker.py) that message appeared on stderr only at exit. In many deployments stderr is not collected at all, so the failure would simply not exist for the team.

I also add a counter metric for failed background jobs, so an alert can fire when the count rises.

"Is a TaskGroup always the answer for background work?"

No. A TaskGroup lives only for the duration of its async with block. That is perfect for "do these three things and wait for all", and wrong for "send the email after the response is returned", because the block would hold the response until the work ends.

Work that outlives a request needs a longer-lived owner. Three options, in rising order of strength:

  1. An app-level set of tasks: created at start-up, with done-callbacks, and drained at shutdown. Fine for work that is cheap to repeat or lose.
  2. An in-process queue with workers: a bounded asyncio.Queue and a few worker tasks. This adds backpressure and a limit on concurrency.
  3. A durable job system: a database table or a message broker (Q142), when the work must survive a restart.

The question I ask is what happens if the process dies in the next second. If losing the job is acceptable, the set is enough. If not, the job must be written down before the response goes out, and an in-memory task is the wrong place.

"Can I cancel everything on shutdown?"

Yes, but only because I kept the set. On shutdown I cancel every task in it, then wait for them to finish their clean-up: await asyncio.gather(*tasks, return_exceptions=True). The return_exceptions=True part matters, since cancelled tasks raise CancelledError and I do not want the first one to abort the wait.

I also give the wait a limit, for example 10 seconds with asyncio.timeout(10), because a task stuck in a blocking call will never respond to cancel (Q85). After the limit I log which tasks did not stop and exit anyway.

Without the set, you have only one safety net. asyncio.run cancels leftover tasks when the main coroutine ends, but it does so with no order and no deadline, and it cannot tell important tasks from unimportant ones. A half-sent email is not helped by that.

So graceful shutdown starts with ownership: if I can list the tasks, I can stop them in order.

Q87. "How do you limit an async program to 10 outbound calls at a time?"

Reveal answer

Strong answer Use an asyncio.Semaphore(10). It is a counter that starts at 10. async with sem: takes one unit, waits if none are left, and gives it back on exit. At most 10 coroutines can be inside the block at once; the rest wait their turn without blocking the loop.

Create the semaphore once and share it, inside the running loop (creating it at import time in older Python versions could bind it to the wrong loop). Wrap only the outbound call, not the whole task, so slots are held as short as possible.

A semaphore bounds concurrency, not the number of tasks. If you create 100,000 tasks up front, all 100,000 exist in memory, and 99,990 wait. For big inputs I use a bounded asyncio.Queue and a fixed number of worker tasks instead (Q92).

Libraries often give a built-in limit too, such as httpx.Limits(max_connections=10). I use the library limit for connections and a semaphore for logic that spans several calls.

Picture it 100 simulated calls of 0.1 s each, limited to 10 at a time. Expected total: 100 / 10 x 0.1 = 1.0 s.

The setup: Each call increments an in-flight counter, sleeps 0.1 s, then decrements. We record the highest value the counter reaches.

semaphore_bound.py · Python 3.14runs offline
import asyncio, time

in_flight = peak = 0

async def call(i, sem):
    global in_flight, peak
    async with sem:
        in_flight += 1
        peak = max(peak, in_flight)
        await asyncio.sleep(0.1)
        in_flight -= 1

async def main():
    sem = asyncio.Semaphore(10)
    t0 = time.perf_counter()
    await asyncio.gather(*(call(i, sem) for i in range(100)))
    print(f"100 calls x 0.1 s, limit 10: {time.perf_counter()-t0:.2f} s, peak in flight = {peak}")

asyncio.run(main())

Make the invisible visible: Run it.

output · Python 3.14runs offline
100 calls x 0.1 s, limit 10: 1.01 s, peak in flight = 10

What you see: The run took 1.01 s, matching the arithmetic, and the peak in-flight count was exactly 10. Without the semaphore all 100 would have run together and finished in about 0.1 s, but would also have opened 100 connections at once.

Unbounded concurrency

All 100 calls start at once.

unbounded.pyruns offline
await asyncio.gather(
    *(call(i) for i in range(100)))

Bounded by a semaphore

At most 10 are inside the block.

bounded.pyruns offline
sem = asyncio.Semaphore(10)
async def call(i):
    async with sem:
        ...

The shift: Concurrency is a resource you grant on purpose, not a default.

Why: The semaphore does not slow work down for its own sake. It trades speed for a promise: the downstream service never sees more than 10 requests from this process at once.

Land it I put an asyncio.Semaphore around the outbound call to cap concurrency, and I switch to a bounded queue with fixed workers when the input is large enough that creating one task per item would itself be the problem.

Likely follow-ups
"Where should the limit be applied: per process or per host?"

The semaphore limits one process, so the system-wide limit is the per-process limit times the number of processes. With 8 worker processes, each using Semaphore(10), the downstream service can see 80 calls at once. If it can only take 20, you will overload it while every process behaves correctly.

So I size it from the budget down. If the downstream allows 40 concurrent requests and I run 8 processes, each gets 5. If the number of processes changes with autoscaling, the limit has to change too, and I read it from configuration instead of a constant. When the budget really is global, I need a shared mechanism, such as a limit in a gateway or a token held in Redis.

For crawling and calling several services, one semaphore per host is better than one global one. A dict of semaphores keyed by host means a slow host cannot use all the slots and starve the others. Q92 shows this with a crawler.

"How is BoundedSemaphore different?"

It adds one safety check. A BoundedSemaphore raises ValueError if you release it more times than you acquired it. A plain Semaphore accepts the extra release and its counter silently grows past the starting value, so your limit of 1 becomes a limit of 2. This run shows both:

q87_bounded.py · Python 3.14runs offline
Semaphore extra release: accepted, counter is now 2
BoundedSemaphore extra release: ValueError: BoundedSemaphore released too many times

With async with sem: a double release cannot happen, because the context manager pairs the two for you. So the difference matters only when code calls acquire() and release() by hand, for example when the release happens in a callback or on a different code path.

In that case I choose the bounded version, because a bug that raises at once is better than a limit that loosens silently and shows up as an overloaded database a week later.

"How do I rate-limit (calls per second) instead of limiting concurrency?"

A semaphore limits how many calls are in flight, not how many start each second. If the calls are fast, a semaphore of 10 still allows many calls per second. At 20 ms per call, 10 slots give 10 / 0.020 = 500 calls per second. If the API allows 100 per second, you will get 429 errors.

For a rate limit I use a token bucket. It holds up to N tokens, refills at a fixed speed, and each call takes one token and waits if none are left. It can be a small class around asyncio.sleep or a library such as aiolimiter.

Often I need both. The two limits protect against different failures:

  1. Rate limiter: keeps the number of starts per second under the provider's quota.
  2. Semaphore: keeps the number of open connections and in-flight requests under what the server and my own memory can take.

A slow provider raises in-flight count even at a low rate, and a fast one raises the rate even at a low in-flight count, so one guard alone is not enough.

"What happens to waiting tasks if the semaphore holder is cancelled?"

The slot is returned. async with sem: runs the exit step when the block ends in any way: normal return, an exception, or a CancelledError. The next waiter in line is then woken and takes the slot.

That gives a useful property. If 10 calls hold slots and a timeout cancels the whole batch, all 10 slots come back, and no later request is blocked by a ghost. With manual acquire() and release() you would have to place the release in a finally block yourself, and a missing one would lose a slot each time. After 10 such failures the limit is zero and every call waits forever.

One more detail concerns waiters. A task that is cancelled while still waiting for a slot is removed from the queue and does not take one. So cancelling a large batch does not leave slots behind.

That is one more reason to use the context manager rather than manual calls.

Q88. "How do you call blocking code from async code, and async code from blocking code?"

Reveal answer

Strong answer Blocking from async: hand the call to a worker thread with await asyncio.to_thread(fn, *args), or await loop.run_in_executor(pool, fn, *args) if I want my own pool or a process pool. The loop stays free while the thread waits. Use this for sync database drivers, requests, file I/O, and CPU work in a process pool.

Async from sync: at the top of a plain program, call asyncio.run(main()) exactly once. It creates a loop, runs the coroutine, and cleans up. Do not call it inside code that is already running in a loop; it refuses.

From a plain thread while a loop runs elsewhere, use asyncio.run_coroutine_threadsafe(coro, loop), which returns a concurrent.futures.Future you can wait on.

The mixing rules are asymmetric: async code can call sync code freely (but must not block), while sync code cannot simply await. That asymmetry is function colouring (Q91).

Picture it Three blocking lookups from async code, then the nested-run mistake.

The setup: blocking_lookup sleeps 0.1 s. We call it three times through to_thread, then try asyncio.run from inside a running loop.

sync_async_bridge.py · Python 3.14runs offline
import asyncio, time, threading

def blocking_lookup(sku):
    time.sleep(0.1)
    return f"{sku}:{threading.current_thread().name}"

async def main():
    r = await asyncio.gather(*(asyncio.to_thread(blocking_lookup, f"s{i}") for i in range(3)))
    print("async -> blocking:", r)

t0 = time.perf_counter()
asyncio.run(main())                         # sync -> async: once, at the top
print(f"3 blocking calls via to_thread took {time.perf_counter()-t0:.2f} s")

async def inside():
    try:
        asyncio.run(main())                 # ❌ TRAP: already inside a loop
    except RuntimeError as e:
        print("nested asyncio.run ->", e)
asyncio.run(inside())

Make the invisible visible: Run it.

output · Python 3.14runs offline
async -> blocking: ['s0:asyncio_0', 's1:asyncio_1', 's2:asyncio_2']
3 blocking calls via to_thread took 0.10 s
nested asyncio.run -> asyncio.run() cannot be called from a running event loop
/home/iam100god/Desktop/AI_COURSE/code/e19-python-deep-dive/E/sync_async_bridge.py:19: RuntimeWarning: coroutine 'main' was never awaited
  print("nested asyncio.run ->", e)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

What you see: The three blocking calls took 0.10 s together because they ran in three different worker threads (asyncio_0, asyncio_1, asyncio_2), not 0.30 s one after the other. The nested asyncio.run raised RuntimeError: asyncio.run() cannot be called from a running event loop. The "never awaited" warning is the inner coroutine that was created but could not be run.

Why: A thread can wait on a blocking call without freezing the loop, because the operating system schedules the thread, not the loop.

Land it I wrap blocking calls in to_thread, call asyncio.run once at the program's entry point, and use run_coroutine_threadsafe when a normal thread needs to submit work to a running loop.

Likely follow-ups
"to_thread or run_in_executor?"

The two functions are close, and the difference is context and flexibility. to_thread(fn, *args) is the short form: it uses the loop's default thread pool and copies the current context variables into the worker thread, so a request id set by middleware is still visible in the thread (Q90).

loop.run_in_executor(pool, fn, *args) lets me choose the executor. I can pass my own ThreadPoolExecutor with a set size, or a ProcessPoolExecutor for CPU work. It does not copy the context, and it takes positional arguments only, so keyword arguments need functools.partial.

My rule:

  1. Default: to_thread for a blocking library call.
  2. Own pool: run_in_executor with a dedicated executor when one slow dependency could use all 16 default threads and starve other work.
  3. Processes: run_in_executor with a process pool for CPU-bound code on a normal build.

Both return an awaitable, so the calling code looks the same.

"How do FastAPI and similar frameworks treat def versus async def handlers?"

The framework decides from how the handler is declared. An async def handler runs directly on the event loop, so any blocking call inside it freezes every other request on that worker. A plain def handler is sent to a thread pool, so blocking inside it is acceptable, and the loop stays free.

Both have limits. The thread pool for def handlers is finite (FastAPI uses AnyIO's pool, 40 threads by default), so 40 slow handlers already fill it and the next one waits. An async def handler is cheap but must use async libraries throughout.

Take a handler that calls requests.get (blocking, 200 ms):

  1. As async def: blocks the loop for 200 ms per call; 40 simultaneous requests finish after 8 s.
  2. As def: runs in threads; the same 40 requests overlap and finish in about 0.2 s.

Picking the wrong form is the single most common cause of the Q82 incident. Chapter E20 covers this in the API setting.

"How do I use await in a Jupyter notebook or REPL?"

In a notebook you write await main() directly at the top of a cell, because Jupyter already runs an event loop and its cell executor lets top-level await work. If you type asyncio.run(main()) there, it fails with RuntimeError: asyncio.run() cannot be called from a running event loop, which is the same rule as above.

The plain Python REPL does not allow top-level await. If you want it, start the asynchronous REPL with python -m asyncio, which runs the loop for you and lets you type await ... at the prompt. It is useful for trying an async client by hand.

In a script file, await outside a function is a syntax error, so a file always needs an async def main() and one asyncio.run(main()) at the bottom.

When I copy a snippet from a notebook into a script, the await lines are the ones I have to wrap first.

"Can I run the loop in a background thread of a sync app?"

Yes, and it is a known pattern for adding async libraries to a program that is mostly synchronous. You start a thread whose job is only loop.run_forever(), keep a reference to the loop, and submit work from other threads with asyncio.run_coroutine_threadsafe(coro, loop). It returns a concurrent.futures.Future, so the sync code can call .result(timeout=5) and wait.

It works, but you are taking on the shutdown work yourself. Someone must stop the loop with loop.call_soon_threadsafe(loop.stop), wait for the thread to end, and cancel the tasks still running. A forgotten thread keeps the process alive. Exceptions in the loop thread need logging, since nobody awaits them.

So my preference is in this order: make the whole program async, or keep the async part behind one small function that uses asyncio.run, or use the background loop only when neither is possible. The background loop is the last choice.

Q89. "What are exception groups and except*?"

Reveal answer

Strong answer An ExceptionGroup (3.11+, PEP 654) is one exception object that carries several exceptions at once. It exists because concurrent code can fail in several places at the same time, and a normal exception can only hold one.

except* is the matching syntax. Each except* clause picks the members of the group that match its type, runs once with a smaller group, and any members nobody matched are re-raised together afterwards. Several except* clauses can run for one raise.

You meet them mainly through asyncio.TaskGroup (Q84), but you can raise your own to report several validation errors at once.

Two rules to remember: a plain except ValueError does not catch a ValueError wrapped inside a group, and you cannot mix except and except* in one try.

Picture it One validation function that reports every problem at once.

The setup: check collects errors in a list and raises them together as one group. The caller handles each type separately.

exception_groups.py · Python 3.14runs offline
def check(order):
    errors = []
    if order["qty"] <= 0:
        errors.append(ValueError("qty must be positive"))
    if order["sku"] is None:
        errors.append(KeyError("sku"))
    if order["price"] < 0:
        errors.append(ValueError("price negative"))
    if errors:
        raise ExceptionGroup("order invalid", errors)

try:
    check({"qty": 0, "sku": None, "price": -1})
except* ValueError as eg:
    print("ValueError branch:", [str(e) for e in eg.exceptions])
except* KeyError as eg:
    print("KeyError branch:", [repr(e) for e in eg.exceptions])

Make the invisible visible: Run it.

output · Python 3.14runs offline
ValueError branch: ['qty must be positive', 'price negative']
KeyError branch: ["KeyError('sku')"]

What you see: Both clauses ran for a single raise. The ValueError clause received a group with two members, the KeyError clause received the third. A normal try/except would have stopped at the first error and hidden the rest.

Why: Collecting errors first and raising a group gives the caller a complete report in one pass, instead of a fix-one-rerun loop.

Land it I describe an exception group as one exception holding many, raised mostly by TaskGroup, and except* as the way to handle each type separately while unhandled ones propagate.

Likely follow-ups
"What happens to members no except* clause matches?"

They are not lost. The members that no except* clause took are collected into a new group, and that group is re-raised after the last clause has run. It keeps the original traceback information, and the group's message, so you still see where each error came from.

Consider a group with a ValueError, a TypeError and a KeyError, and a try block with clauses for ValueError and KeyError only. Both clauses run, one with each matching member, and an ExceptionGroup holding the TypeError goes up to the caller.

This design means a handler can deal with the errors it understands and let the others pass, the same way a normal except lets other exception types pass. The difference is that the leftover is smaller than the original.

The consequence I plan for is that the outer layer must expect a group, and logging code must print every member, not just the group's top-level message.

"Can I use return, break or continue inside except*?"

No. Using return, break or continue inside an except* block is a syntax error. The reason is that several except* clauses can run for a single raise. A return in the first would skip the others, and it would be unclear what happens to the members still waiting to be handled or re-raised.

The way around it is to record what you learned and act after the whole try statement:

  1. Collect: in each clause, append to a list or set a flag, for example failed.append(...).
  2. Finish the try: let all clauses run, and the leftover group propagates.
  3. Decide after: after the block, if the list is not empty, return a fallback value or break out of the loop.

Raising a new exception from inside an except* block is allowed, and it is combined with whatever else is being raised, so use it for translating errors, not for flow control.

"How do I inspect or split a group without except*?"

Without except*, the group object has three tools. eg.exceptions is a tuple of the members, which may themselves be groups. eg.split(ValueError) returns a pair of groups, the matching part and the rest (either may be None if empty). eg.subgroup(ValueError) returns just the matching part.

q89_split.py · Python 3.14runs offline
ExceptionGroup('batch', [ValueError('a'), ValueError('c')])
ExceptionGroup('batch', [TypeError('b')])
3 members in the original

Both halves keep the group's message, 'batch', and the original order. The original is not changed.

Groups can be nested, because a TaskGroup inside a TaskGroup produces a group inside a group. When I log, I walk the tree recursively and print every leaf with its traceback, since the top-level message only says "2 sub-exceptions" and hides the cause.

"Does this change how I write library code?"

Mainly for async libraries, and the effect is visible at the boundary. If my library runs its children in a TaskGroup, a failure now reaches the caller as an ExceptionGroup, even when only one child failed. A caller who wrote except TimeoutError will not catch it any more, and that is a breaking change in behaviour even if no signature changed.

I have two honest options:

  1. Document it: say in the docs that the function may raise an ExceptionGroup, and show an except* example.
  2. Unwrap at the edge: if the group has exactly one member, raise that member, so the public API keeps the exception type callers expect. For several members, raise the group.

I choose the second for a library with many existing users, and the first for new code. Either way the decision is made on purpose, and it goes into the changelog.

For application code that owns its callers, I simply handle groups with except* at the top of the request.

Q90. "contextvars versus threading.local — why does asyncio need contextvars?"

Reveal answer

Strong answer threading.local gives each thread its own copy of a value. That is right when one request equals one thread. In asyncio, many requests share one thread, so a thread-local value is shared by all of them and they overwrite each other.

contextvars.ContextVar gives each context its own value. A context is copied when a task is created, so every task starts with a snapshot of its parent's values and then changes only its own copy. The loop switches the active context whenever it switches tasks.

Use it for request-scoped data that many layers need but nobody wants to pass as a parameter: request id, current user, tenant, tracing span. Set it once at the edge (middleware); read it anywhere below, including in log filters.

A ContextVar works in plain threads too, and to_thread copies the current context into the worker thread, so one tool covers both models.

Picture it Two concurrent handlers that each store their request id and read it back after an await.

The setup: Both handlers set request_id and local.rid, then sleep 10 ms so the other handler runs in between.

ctx_vs_local.py · Python 3.14runs offline
import asyncio, contextvars, threading

request_id = contextvars.ContextVar("request_id", default="-")
local = threading.local()

async def handler(rid):
    request_id.set(rid)
    local.rid = rid
    await asyncio.sleep(0.01)             # other tasks run here
    print(f"  {rid}: contextvar={request_id.get()}  threading.local={local.rid}")

async def main():
    await asyncio.gather(handler("req-A"), handler("req-B"))

asyncio.run(main())

Make the invisible visible: Run it.

output · Python 3.14runs offline
  req-A: contextvar=req-A  threading.local=req-B
  req-B: contextvar=req-B  threading.local=req-B

What you see: The context variable returned each handler's own id. The thread-local value in req-A's handler reads req-B: it was overwritten while A was sleeping, because both tasks live in one thread.

Make the invisible visible: The same variable feeding a logging filter, so every line carries the request id without passing it around.

json_logging.py · Python 3.12runs offline
{"ts": "15:36:59", "level": "INFO", "logger": "pricer", "request_id": "req-123", "msg": "pricing started"}
{"ts": "15:36:59", "level": "ERROR", "logger": "pricer", "request_id": "req-123", "msg": "pricing failed"}

threading.local in async code

One slot per thread, many tasks.

local.pyruns offline
local = threading.local()
local.rid = rid
await step()
print(local.rid)  # maybe another's

ContextVar

One slot per task context.

ctx.pyruns offline
rid_var = ContextVar("rid")
rid_var.set(rid)
await step()
print(rid_var.get())  # own value

The shift: State that belongs to a request must live in the request's context, not the thread's.

Why: The logging code never received the id as an argument. The filter read it from the context, which is why contextvars is the standard way to correlate logs (Q145).

Land it I use contextvars for request-scoped data in async code because each task gets its own copy, while threading.local is per thread and gets overwritten when tasks share a thread.

Likely follow-ups
"When exactly is the context copied?"

The context is copied at one moment: when a task is created, through create_task or TaskGroup.create_task, and when to_thread starts a worker. The child gets a snapshot of the values at that moment, not a live link.

After that the two are independent. A change in the child does not reach the parent, and a later change in the parent does not reach the child. This run shows the three cases:

q90_context_snapshot.py · Python 3.14runs offline
child starts with  : req-1
after separate task: req-1
after plain await  : set-in-helper

The child saw the parent's value at creation time. The child's set did not come back. But the helper awaited directly runs in the caller's own context, so its set is visible after the call.

This surprises people who set a variable in a helper task and expect the caller to see it. If the caller needs a value back, return it.

"What are set tokens and reset for?"

var.set(x) returns a token, an object that remembers what the value was before the call. var.reset(token) puts that old value back. It is not the same as setting the old value by hand, because the token also restores the state of "never set", where the variable falls back to its default.

The common use is in middleware that wraps each request:

  1. Set: token = request_id.set(new_id) at the start of the request.
  2. Run: call the next handler; everything below reads request_id.get().
  3. Reset: in a finally block, request_id.reset(token).

The reset matters whenever a worker runs several requests in the same context, for example a thread-pool worker or a long-lived task that handles a loop of messages. Without it, request 2 could start with the id of request 1 and write logs under the wrong identity.

It is a small habit with a clear payoff: a wrong request id in a log is worse than none, because it sends the on-call engineer to the wrong trace.

"Is a mutable default safe for a ContextVar?"

No, for the same reason as a mutable default argument (Q3). ContextVar("items", default=[]) creates one list when the variable is defined, and every context that has not set its own value gets that same list. An append in one request then shows up in all the others, in effect a global shared by every request.

A short scenario. Two requests both call items.get().append("x") without ever calling set. The default list has now grown to two elements, and each request sees both, including the one that was not its own. That can leak data between tenants, which is a security problem, not just a bug.

The rule I use is simple:

  1. Default: something immutable, such as None, "-" or a tuple.
  2. Per request: in the middleware, set a fresh list or object for this request and store its token.
  3. Readers: treat None as "not inside a request".
"Why not just pass the request id as a parameter?"

For business data I do pass it as a parameter. An order id or a price is part of what the function computes, so it should be visible in the signature, where it can be tested and typed.

Cross-cutting data is different: a request id, the current user for audit, a trace span. These are needed by log lines and metrics in every layer. Passing them as a parameter means adding it to every function between the edge and the log call, say 6 layers, plus callbacks from third-party libraries that I cannot change to accept it.

A context variable avoids that, at the price of being implicit. A function that reads request_id.get() works differently depending on where it is called from, and a test must set the variable first. That is a real cost.

My compromise is a short, well-known list of context variables, perhaps three, each set in one place (middleware) and read mostly by logging and tracing code. Everything else goes through parameters, so the program's real inputs stay visible.

Q91. "Java virtual threads versus Python asyncio — what is "function colouring"?"

Reveal answer

Strong answer Function colouring is a phrase from an essay by Bob Nystrom. Imagine every function is either red (async def) or blue (plain def). A red function can call a blue one freely. A blue function cannot simply call a red one and get a result; it gets a coroutine object. So the colour spreads: once a low-level function becomes async, everything that calls it must become async too.

Python asyncio has colours. Async code is cooperative: it must use await, async libraries (httpx.AsyncClient, asyncpg), and must never block the loop. You choose between two worlds, and mixing needs bridges (Q88). Java virtual threads (Java 21) do not have colours. A virtual thread is a very cheap thread managed by the JVM. When it does blocking I/O, the JVM unmounts it from its carrier thread and runs another one, so you write ordinary blocking code, with stack traces and debuggers that work normally, and still serve a hundred thousand concurrent waits.

The trade-off: asyncio gives explicit suspension points (you can see where a task may be paused, and nothing else can interleave in between), while virtual threads give simple code but shared mutable state needs the usual locks everywhere.

Picture it The same task, "look up 100 items concurrently", in both worlds. Then what colouring looks like in Python.

Java 21 · virtual threads

Plain blocking code. repo.find is an ordinary method; the JVM parks the virtual thread while it waits.

Orders.javaruns offline
try (var ex = Executors
    .newVirtualThreadPerTaskExecutor()) {
  for (var id : ids) {
    ex.submit(() -> repo.find(id));
  }
} // close() waits for all

Python · asyncio

Every function on the path must be async def and awaited. A blocking find would stall the loop.

orders.pyruns offline
async def find_all(ids):
    async with asyncio.TaskGroup() as tg:
        for i in ids:
            tg.create_task(
                repo.find(i))  # async!

The shift: Java hides the waiting inside the runtime so any blocking method works; Python makes waiting visible in the type of the function, so every caller must opt in.

Make the invisible visible: What happens when a blue (plain) function calls a red (async) one, run for real.

colour.py · Python 3.14runs offline
import asyncio

async def fetch_price(sku):
    await asyncio.sleep(0.01)
    return 4.5

def report_sync():
    price = fetch_price("A1")             # ❌ TRAP: a "red" function called from a "blue" one
    print("price is:", price)

def report_right():
    price = asyncio.run(fetch_price("A1"))   # sync code must start a loop to cross over
    print("price is:", price)

report_sync()
report_right()
output · Python 3.14runs offline
/home/iam100god/Desktop/AI_COURSE/code/e19-python-deep-dive/E/colour.py:15: RuntimeWarning: coroutine 'fetch_price' was never awaited
  report_sync()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
price is: <coroutine object fetch_price at 0x7c266780ce10>
price is: 4.5

What you see: Calling fetch_price from plain code printed a coroutine object and a "never awaited" warning: no price. The only way across is asyncio.run, which starts a loop.

Why: This is the cost of explicit async: colour spreads through your call graph. The benefit is that suspension points are visible and cheap, with no thread stacks.

Land it I describe colouring as async def versus def being a contagious split in the call graph, and I say virtual threads avoid it by making blocking cheap, while asyncio makes every wait explicit and keeps one thread's state single-threaded between awaits.

Likely follow-ups
"Does asyncio still have a place in a world with virtual threads?"

In Python, yes, because Python has no virtual threads. A real operating-system thread reserves stack memory (often around 8 MB of address space by default on Linux, though only the part used is committed), and the OS must schedule it. A few hundred threads is fine; tens of thousands is not. On top of that, the GIL means those threads do not run Python in parallel anyway.

A coroutine is a small heap object, so a single thread can hold tens of thousands of waiting requests. That is why asyncio is how Python reaches high connection counts.

In Java the picture changed in version 21. A virtual thread is cheap enough to create one per request, and ordinary blocking code scales. For many services the reason to choose reactive code is then no longer thread cost.

What remains for reactive style is backpressure and streaming operators, where a pipeline of stages controls how fast data flows. So my answer: in Python asyncio is the main tool for many waits, and in Java it is a choice about programming style.

"Can virtual threads block the carrier threads?"

Sometimes, yes. The JVM runs virtual threads on a small pool of carrier threads. When a virtual thread blocks on I/O, it is unmounted and the carrier runs another one. That works only if the virtual thread can be unmounted. If it is blocked while holding a synchronized monitor, or inside a native call, it is pinned: it keeps the carrier thread, which then cannot run anyone else.

If you have 8 carriers and 8 virtual threads pinned in slow calls, the whole application stops serving, though thousands of other virtual threads are ready.

  1. Check the JDK release: newer releases reduce pinning for synchronized, so I read the release notes for the version I use rather than rely on memory.
  2. Prefer ReentrantLock: in hot paths that wait, since it cooperates with unmounting.
  3. Look for pinning: the JVM can report it with a diagnostic flag or flight-recorder event.

The Python parallel is a blocking call inside async def: one stalled worker holds back the rest.

"What are the practical rules to live with colouring in Python?"

I treat it as a design choice made once per service, plus a few clear bridges.

  1. Pick a world: an async framework means async clients end to end, such as httpx.AsyncClient and an async database driver. A sync service means plain clients and threads. Half-and-half code is where the bugs live.
  2. Bridge at the edges: asyncio.run once in main, and to_thread for the one blocking library that has no async version.
  3. Do not spread bridges: a helper that calls asyncio.run creates a new loop on every call, which is slow, and it fails when a loop is already running.

For a library that must serve both worlds, I write the core once as plain functions with no I/O, and add two thin wrappers on top, one sync and one async. Duplicating wrappers is cheaper than contaminating the core.

A habit that helps is a name suffix for async functions, so the colour is visible at the call site.

"Is there any Python-side way to avoid colouring?"

There is one approach, and it has a cost. Libraries such as gevent patch the standard blocking calls (sockets, sleep) so that they yield to a scheduler. Plain, ordinary-looking code then runs concurrently, with no async or await. It is the nearest thing in Python to what virtual threads give Java.

The price is monkey-patching, which means replacing parts of the standard library at start-up. It works for pure-Python code, but a C extension that blocks inside its own native code is not patched, and it blocks everyone. Debugging is also harder, since the scheduling is hidden.

Free-threaded Python (3.14t) approaches the problem from the other side. Plain threads can run truly in parallel, which removes the CPU-bound reason to avoid them. For waiting-heavy work, threads still cost much more than coroutines, so colouring does not disappear for a service with ten thousand open connections.

I would use gevent only for an existing code base that needs concurrency without a rewrite.

Q92 · Design. "Design an async crawler for 100,000 URLs: per-host limits, retries, timeouts and backpressure."

Reveal answer

Strong answer I design it as a pipeline with bounded queues and a fixed number of workers, not as 100,000 tasks. The parts: a frontier queue (bounded, so the producer waits when workers are busy), N workers that pull a URL, a semaphore per host so one site is never hit by more than a few requests at once, a timeout around every request, and retries with exponential backoff and jitter for transient errors only.

Sizing uses Little's law: concurrency = throughput x latency. To fetch 100,000 pages at 0.5 s each with 40 workers, the run takes 100,000 x 0.5 / 40 = 1,250 s, about 21 minutes. For a target of 5 minutes I need about 170 in flight, but also respect host limits: if one host has 30,000 URLs and allows 3 at once, that host alone takes 30,000 x 0.5 / 3 = 5,000 s. Host politeness, not worker count, becomes the limit.

Retry only what is safe and useful: timeouts, connection resets, 429 (obeying Retry-After) and 5xx. Never retry 4xx except 429. Cap attempts (3) and record URLs that gave up.

Backpressure comes from await queue.put(url) blocking when the queue is full, and from a bounded results queue to the writer. Also cap response size, skip non-HTML content types, de-duplicate URLs with a set, honour robots.txt, and checkpoint the frontier so a restart does not begin again.

Picture it A scaled-down simulation: 400 URLs over 4 hosts, 40 workers, 3 per host, 0.3 s timeout, 15 percent of requests hang, 5 percent reset.

The setup: fake_fetch stands in for httpx.AsyncClient.get. The structure around it is the real design.

crawler_sim.py · Python 3.14runs offline
import asyncio, random, time
from collections import Counter
from urllib.parse import urlsplit

random.seed(7)
HOSTS = ["a.test", "b.test", "c.test", "d.test"]
URLS = [f"https://{random.choice(HOSTS)}/p{i}" for i in range(400)]
GLOBAL_LIMIT, PER_HOST, QUEUE_MAX, RETRIES, TIMEOUT = 40, 3, 50, 3, 0.3

stats = Counter(); host_now = Counter(); host_peak = Counter()

async def fake_fetch(url):            # stands in for httpx.AsyncClient.get
    roll = random.random()
    await asyncio.sleep(random.uniform(0.02, 0.08) if roll > 0.15 else 1.0)  # 15% hang
    if roll < 0.05:
        raise ConnectionError("reset")
    return 200

async def fetch(url, host_sems):
    host = urlsplit(url).hostname
    for attempt in range(1, RETRIES + 1):
        async with host_sems[host]:
            host_now[host] += 1; host_peak[host] = max(host_peak[host], host_now[host])
            try:
                async with asyncio.timeout(TIMEOUT):
                    await fake_fetch(url)
                stats["ok"] += 1
                return
            except (TimeoutError, ConnectionError):
                stats["retry"] += 1
            finally:
                host_now[host] -= 1
        await asyncio.sleep(0.05 * 2 ** attempt * random.random())   # backoff + jitter
    stats["gave_up"] += 1

async def worker(q, host_sems):
    while (url := await q.get()) is not None:
        await fetch(url, host_sems)

async def main():
    q = asyncio.Queue(maxsize=QUEUE_MAX)                 # backpressure
    host_sems = {h: asyncio.Semaphore(PER_HOST) for h in HOSTS}
    t0 = time.perf_counter()
    async with asyncio.TaskGroup() as tg:
        for _ in range(GLOBAL_LIMIT):
            tg.create_task(worker(q, host_sems))
        for u in URLS:
            await q.put(u)                               # blocks when queue is full
        for _ in range(GLOBAL_LIMIT):
            await q.put(None)
    print(f"{len(URLS)} urls in {time.perf_counter()-t0:.1f} s  {dict(stats)}")
    print("peak concurrent per host:", dict(host_peak))

Make the invisible visible: Run it.

output · Python 3.14runs offline
400 urls in 4.6 s  {'ok': 399, 'retry': 77, 'gave_up': 1}
peak concurrent per host: {'c.test': 3, 'b.test': 3, 'd.test': 3, 'a.test': 3}
# measured on the course machine; your numbers will differ

What you see: All 400 URLs were handled in 4.6 s. 77 attempts were retried (the hangs timed out at 0.3 s and the resets were retried), and one URL gave up after three attempts. The peak concurrency per host was 3 for every host: the per-host limit held even though 40 workers were running.

data flowruns offline
# illustrative
URL source -> [frontier Queue(maxsize=50)] -> 40 workers
                   |  put() blocks when full       |
                   |                              v
                   |                host semaphore(3) -> timeout(0.3 s) -> fetch
                   |                              | ok         | error
                   |                              v            v
                   +------ backpressure <-- [results Queue]   retry with backoff + jitter

Why: Each limit protects something different: the queue protects your memory, the host semaphore protects the target, the timeout protects your workers from hanging peers, and the retry cap protects everyone from a retry storm.

Land it I build the crawler as a bounded queue feeding a fixed set of workers, with a semaphore per host, a timeout on every request, capped retries with jittered backoff, and a size check on the numbers using Little's law.

Likely follow-ups
"How do you pick the number of workers?"

I start with Little's law, which says that the number of requests in flight equals the rate you want multiplied by the time each takes. It is a simple relation that applies to any queue.

Little's lawruns offline
in flight = rate x latency
200 pages/s x 0.5 s = 100 workers
5 min target for 100,000 pages: 333 pages/s x 0.5 s = about 167 in flight

That is the first number. Then I cap it by the limits that sit outside my code: open file descriptors on the machine, the speed of DNS lookups, my bandwidth, and what each target host allows. If one host holds 30,000 of the URLs and allows 3 at once, the per-host limit decides the total time, not the worker count.

I then measure. If latency rises when I add workers, the targets are the bottleneck, and extra workers only add errors and timeouts. I stop where throughput stops growing.

"Why jitter on the backoff?"

Without jitter, every failed request retries after exactly the same delay: 0.1 s, then 0.2 s, then 0.4 s. If 1,000 requests failed at the same moment because a host hiccuped, all 1,000 come back together at 0.1 s, and again together at 0.2 s. The retries arrive in synchronised waves, which can knock down a host that was only just recovering.

Jitter adds a random factor so the retries spread out over time. The demo uses 0.05 * 2 ** attempt * random.random(): the delay grows exponentially with the attempt number, and the random part picks anywhere between zero and that value. For attempt 3, the wait is anywhere from 0 to 0.4 s.

  1. Cap it: a maximum delay, such as 30 s, so a high attempt number does not wait for minutes.
  2. Limit attempts: three is a common choice. Then record the URL as failed.
  3. Obey the server: if it sends Retry-After, wait at least that long.
"What if the results writer is slower than the crawlers?"

The writer sets the real speed of the pipeline, so I let it slow the fetchers instead of letting memory grow. I put the results on a bounded queue, say 1,000 items. When the writer falls behind, the queue fills, the workers block on await queue.put(result), and fetching slows to the speed the writer can sustain.

Without the bound, the queue is a buffer with no limit. If the crawlers produce 200 pages per second at 50 KB each, that is 10 MB per second of results. A writer running at half speed lets the backlog grow 5 MB per second, 300 MB per minute, until the process runs out of memory.

If the writer does blocking I/O, such as a sync database driver, it must not run on the event loop. I run it in a thread (to_thread) or a separate process, and the queue is how the loop hands items over.

I also write results in batches, for example 500 rows per insert, since one insert per page is far slower than batched ones.

"How do you make it restartable?"

I make progress durable, and I make every step safe to repeat. The frontier (the URLs still to fetch) and a "done" marker per URL are stored in a database table or a file, and each time the program starts it loads the pending ones.

  1. Record state: a row per URL with a status: pending, in progress, done, failed, plus the attempt count.
  2. Mark done after saving: set "done" only after the result is stored, so a crash in between causes a repeat, never a loss.
  3. Reset on start: rows left "in progress" by a crashed run go back to pending.

Repeating is harmless because a GET request is idempotent, meaning the same request twice has the same effect as once, and I store results with the URL as the key. A second write replaces the first with the same content.

I also write progress in batches, say every 1,000 URLs, rather than after every one. A restart then repeats up to 1,000 fetches, which is a small, known price for a much cheaper checkpoint.

Drill · Threads, processes and interpreters

Here the test is the decision rule: what does the work wait on, what does each model share, and what does each cost. Expect follow-ups with numbers.

Q93. "Threads, processes, asyncio, subinterpreters, free-threading — what is your decision rule?"

Reveal answer

Strong answer I start from what the program waits on, then check the answer with a measurement.

Mostly waiting on the network or disk, many connections: asyncio, with async libraries. Cheapest per task, tens of thousands in one thread. Waiting, but the library is blocking and concurrency is modest (tens): a thread pool; the GIL is released while a thread waits on I/O. CPU-bound Python code: on the regular build, threads give no speed-up, so use processes (separate memory, pickling cost), or push the loop into native code (numpy, Cython, Rust). Newer options: subinterpreters (3.14, separate GIL per interpreter, lighter than processes, no shared objects) and the free-threaded build (3.14t, threads run Python in parallel, shared memory, but a separate build and some extension modules not ready).

A mixed service is normal: asyncio at the edge, a process pool for the CPU-heavy part, to_thread for the one blocking library.

Picture it The same four CPU-bound jobs run serially and on four threads, on the regular 3.14 and the free-threaded 3.14t.

The setup: work(3,000,000) is pure Python arithmetic. Four jobs, serial then ThreadPoolExecutor(4).

cpu_models.py · Python 3.14 and 3.14truns offline
import sys, time
from concurrent.futures import ThreadPoolExecutor

def work(n):
    total = 0
    for i in range(n):
        total += i * i % 7
    return total

N, JOBS = 3_000_000, 4
gil = getattr(sys, "_is_gil_enabled", lambda: True)()
t = time.perf_counter(); [work(N) for _ in range(JOBS)]; serial = time.perf_counter() - t
with ThreadPoolExecutor(JOBS) as ex:
    t = time.perf_counter(); list(ex.map(work, [N] * JOBS)); threads = time.perf_counter() - t
print(f"{sys.version.split()[0]} GIL enabled={gil}: serial {serial:.2f} s | {JOBS} threads {threads:.2f} s | speed-up {serial/threads:.1f}x")

Make the invisible visible: Two runs on each build (the first two lines of each pair: regular, free-threaded).

output · Python 3.14 / 3.14truns offline
3.14.7 GIL enabled=True: serial 0.78 s | 4 threads 2.12 s | speed-up 0.4x
3.14.7 GIL enabled=False: serial 0.87 s | 4 threads 0.23 s | speed-up 3.8x
3.14.7 GIL enabled=True: serial 0.76 s | 4 threads 2.02 s | speed-up 0.4x
3.14.7 GIL enabled=False: serial 0.88 s | 4 threads 0.23 s | speed-up 3.9x
# measured on the course machine (12 cores); your numbers will differ

What you see: On the regular build four threads took about 2.1 s against 0.77 s serial: slower (0.4x), because the threads fight for the GIL. On the free-threaded build four threads took 0.23 s, about 3.8x faster. Serial speed is also a little lower on 3.14t (0.87 against 0.77 s, about 13 percent in this run; section 05 measured about 23 percent with a different loop, so the cost depends on the code), the price of the thread-safe design.

Make the invisible visible: The rule as a picture, with the measured costs from this chapter's demos.

decision ruleruns offline
# illustrative
what does the work wait on?
|-- network / disk, async libraries available ... asyncio          (Q82: 40 requests in 51 ms)
|-- network / disk, blocking library .............. thread pool    (to_thread: 106 ms)
|-- CPU, Python code
|     |-- split into big, independent jobs ........ processes      (Q95: 0.82 s -> 0.24 s)
|     |-- need shared memory, build is OK ......... free-threaded    (this page: 0.88 s -> 0.23 s)
|     |-- isolated workers, light start-up ........ subinterpreters (Q97)
|     \-- the loop is numeric ..................... numpy / Cython / Rust (Q108)

Why: The decision is not a matter of taste. Each model changes what is shared and what a task costs, and those two facts decide which bugs and which overheads you get.

Land it I choose by what the work waits on: asyncio for many I/O waits, threads for blocking libraries, processes or native code for CPU on the regular build, and I measure, because free-threading and subinterpreters change the CPU answer.

Likely follow-ups
"When would you adopt the free-threaded build?"

I would adopt it when four conditions are all true. The work is CPU-bound Python. The threads need to share large in-memory data, so that copying it to processes would be expensive. I have measured the gain on my own code. And every dependency, especially compiled extensions, works on 3.14t.

The costs are real. This chapter measured single-thread overhead of about 13 percent in one test and 23 percent in the pricing benchmark. The build is separate, which means its own images, wheels and monitoring. And the races that the GIL hid, such as counter += 1, now appear.

A worked example with the pricing numbers: 0.84 s on one thread of 3.14t against 0.70 s on 3.14, then 0.25 s on four threads. Net gain over the normal build's best, 0.70 s, is about 2.8 times. That is a good result, but a process pool on the normal build might get close, using more memory.

So I compare it with the process pool first, and adopt it only if shared memory is the deciding factor.

"What are subinterpreters good for?"

They are good when I want CPU parallelism and isolation, but processes feel heavy. Each interpreter in concurrent.interpreters has its own GIL and its own objects, inside one operating-system process. Because each has its own lock, several can run Python code at the same time on several cores.

They are cheaper than processes. Creating one is faster than starting a new Python process, and the memory overhead is lower, since the process-level resources are shared. Nothing is shared at the object level, so there are no data races on Python objects.

The trade-off is that data cannot be passed by reference. Arguments and results are copied, or sent through special shareable types, such as the interpreter queue. A 500 MB array would be copied, so interpreters suit many small messages and independent jobs better than large shared data.

Also, a C extension must support being loaded in several interpreters. Q97 shows the API.

"Why not always use processes?"

Because every task pays a fixed price, and with processes that price is high. A worker must be started (tens of milliseconds, since each imports your modules under spawn or forkserver), each memory copy takes space, and every argument and result is pickled and sent through a pipe.

When the task is tiny, that overhead is larger than the work. If one item takes 2 microseconds and sending it costs 50 microseconds, then four processes spend 25 times more on messages than on computing, and the pool is slower than a plain loop. Q95 shows this.

The break-even rule I use: the work in one task should be at least several milliseconds, and preferably tens, so the overhead is a few percent. For tiny items I batch many into one task.

Processes also have a memory cost. Eight workers that each import a 300 MB library use about 2.4 GB, where eight threads would share one copy.

Processes pay off when each task is big, and its inputs and outputs are small.

"How do you tell I/O-bound from CPU-bound in practice?"

I measure the CPU use while the service handles realistic load, then look at where the time goes.

  1. CPU view: one core at 100 percent while the others are idle means CPU-bound in a single Python process, and the GIL is the limit. Low CPU with high latency means the program is mostly waiting.
  2. Thread view: py-spy shows what each thread is doing. If most samples sit in recv, select or a database call, it is waiting. If they sit in your own functions, it is computing.
  3. Profile: a profiler (Q104) breaks down time by function and shows whether the cost is Python code or a waiting call.

A quick experiment also helps: run the same job with 1 and 4 threads. If four threads give about 4 times the speed, the work was waiting. If they give 1 times, it was computing under the GIL.

Real services are usually a mix, so I look at the largest share of time first.

Q94. "multiprocessing start methods fork, spawn and forkserver — and what changed in 3.14?"

Reveal answer

Strong answer A start method is how a new worker process gets created.

fork: the operating system copies the whole parent process. Fast, and the child sees the parent's memory as it is at that moment, including modules, globals and open files. The danger: only the forking thread survives in the child, while locks held by other threads stay locked forever (Q96). spawn: start a fresh Python interpreter, import the main module again, then send the function and arguments by pickling. Slow to start, but clean and safe. It is the default on Windows and macOS, so code that works on a Linux laptop with fork can break there. forkserver: at first use, start one small clean server process; each worker is forked from that server, not from your big, threaded program. Safer than fork, faster than spawn. In 3.14 the Linux default changed from fork to forkserver. I verified this by running both interpreters here.

Picture it What the default is, and what each method lets the child see.

Make the invisible visible: Ask both interpreters.

start_methods.py · Python 3.12 and 3.14runs offline
3.12.3 default start method: fork | available: ['fork', 'spawn', 'forkserver']
3.14.7 default start method: forkserver | available: ['forkserver', 'fork', 'spawn']

What you see: Python 3.12.3 defaults to fork on this Linux machine. Python 3.14.7 defaults to forkserver. The first item in the list is the default.

The setup: The parent changes a global CONFIG after the module was imported, then starts a child that prints what it sees.

start_diff.py · Python 3.14runs offline
import multiprocessing as mp, os

CONFIG = {"tax": 0.2}                     # set at import time

def child(q):
    q.put((os.getpid(), dict(CONFIG)))

def run(method):
    ctx = mp.get_context(method)
    CONFIG["tax"] = 0.5                   # changed AFTER import, in the parent only
    q = ctx.Queue(); p = ctx.Process(target=child, args=(q,)); p.start()
    pid, seen = q.get(); p.join()
    print(f"{method:10} child sees CONFIG = {seen}")
    CONFIG["tax"] = 0.2

if __name__ == "__main__":
    for m in ("fork", "spawn", "forkserver"):
        run(m)
output · Python 3.14runs offline
fork       child sees CONFIG = {'tax': 0.5}
spawn      child sees CONFIG = {'tax': 0.2}
forkserver child sees CONFIG = {'tax': 0.2}

What you see: fork copied the changed memory (tax: 0.5). spawn and forkserver re-imported the module, so the child saw the original 0.2. Code that relied on fork copying state silently changes behaviour on 3.14.

fork: copy of the parent

Fast; copies memory and held locks.

fork.pyruns offline
ctx = mp.get_context("fork")
p = ctx.Process(target=f)
p.start()  # sees parent's globals

forkserver: fresh child

Clean start; state must be passed in.

forkserver.pyruns offline
ctx = mp.get_context("forkserver")
p = ctx.Process(target=f, args=(cfg,))
p.start()

The shift: Fork inherits whatever the parent was doing; forkserver inherits only what you pass.

Why: A pool created with fork inherits whatever the parent has done; spawn and forkserver start from the module as imported. Pass what the child needs as arguments, and keep module-level state read-only.

Land it I explain fork as copy-everything, spawn as fresh-start, and forkserver as fork from a clean helper, I mention that the Linux default became forkserver in 3.14, and I make worker code importable and its inputs explicit.

Likely follow-ups
"What breaks when I upgrade to 3.14 with multiprocessing?"

Three things can break, and each has a clear check. The first is that workers no longer inherit changes made to globals at run time. With fork, a child saw the parent's memory as it was at that moment, so a global set by main() before the pool started was visible. With forkserver or spawn, the child starts clean and re-imports modules, so the global has its original value.

  1. Pickling: the function and arguments must be picklable. Lambdas, nested functions, open sockets and connections are not.
  2. Import safety: the main module is imported again in each worker, so start-up code must sit under if __name__ == "__main__": (Q73), or each worker re-runs it and may start new pools.
  3. Hidden state: anything that worked because a child inherited it, such as a configured logger or a loaded model, must now be created in the worker.

If I truly need the old behaviour, multiprocessing.get_context("fork") asks for it, knowing the thread-safety caveat from Q96.

"What can I not pass to a worker?"

Anything pickle cannot turn into bytes. The usual list is lambdas, functions defined inside other functions, open sockets, database connections, file handles, thread locks, and generators. The error appears when the task is sent, not when the worker starts.

This run sends a top-level function and a nested one, under both fork and forkserver:

nested_target.py · Python 3.14runs offline
fork       top-level function: [2, 4, 6]
fork       nested function   : PicklingError: Can't pickle local object <function main.<locals>.nested at 0x7fd08b7a3320>
forkserver top-level function: [2, 4, 6]
forkserver nested function   : PicklingError: Can't pickle local object <function main.<locals>.nested at 0x7fd08b32eda0>

Pickle sends a function by its importable name, so the function must be reachable at the top of a module. The fix is a top-level function plus plain-data arguments. A worker that needs a database connection opens its own, in an initializer, not in the parent.

"Why was fork a problem enough to change a default?"

Because most real programs are not single-threaded. A logging thread, a metrics exporter, a connection pool's helper, or a library's background thread are all common. With fork, only the calling thread is copied. If any other thread holds a lock at that instant, the child has the lock in a locked state, and nobody exists to release it.

The result is a worker that hangs on its first use of that lock, with no error and no CPU use. It is also rare: if the fork lands outside the short moment the lock is held, nothing happens, so the bug appears in production under load, not in a test.

The warning came in two steps. Python 3.12 started to emit a DeprecationWarning when a multi-threaded process forks. In 3.14 the Linux default changed to forkserver, which forks from a small clean helper that has no other threads.

Q96 reproduces the deadlock. The default change protects people who never read the warning.

"When would I still choose fork?"

When start-up cost dominates and the program is single-threaded at the time of the fork. The classic case is a large read-only structure, such as a 2 GB model or lookup table, that is loaded once. With fork, the child process shares those memory pages with the parent without copying, as copy-on-write (pages are copied only when written).

With spawn or forkserver, each of 8 workers would load the model again: 8 times the time, and, unless it is memory-mapped, 8 times the memory.

Two cautions. First, reference counting writes to object headers whenever a worker touches an object, even to read it, so the shared pages are copied gradually, and memory use creeps up. Calling gc.freeze() before the fork moves existing objects out of the collector's reach and helps limit that (Q17).

Second, I make sure no other threads exist at the time, and I request fork explicitly with get_context("fork"), so the choice is visible in the code.

Q95 · Scenario. "A ProcessPoolExecutor job runs slower than the single-process version. Why?"

Reveal answer

Strong answer Because every task pays a fixed overhead that is larger than the work in it. To send one item to a worker process, Python pickles the arguments, writes them to a pipe, a worker reads and unpickles them, runs the function, pickles the result and sends it back. That round trip costs tens to hundreds of microseconds.

If the work itself is a multiplication that takes a fraction of a microsecond, the overhead is thousands of times bigger than the work, and four processes just spend four times as much time passing messages.

The fix: make each task big. Group items into chunks (ex.map(f, data, chunksize=500), or send a slice of the list as one task), and send small inputs and results. For heavy tasks processes do pay off, up to the number of real cores.

Other causes of a slow pool: shipping large objects every time (a big DataFrame pickled per task), more workers than cores, start-up cost for tiny jobs, and a serial part that dominates (Amdahl's law).

Picture it The same squaring job three ways, then a genuinely heavy job.

The setup: 20,000 tiny items (one multiplication each). Serial loop, pool with one item per task, pool with chunks of 500. Then 8 heavy jobs, serial and on 4 processes.

pool_overhead.py · Python 3.14runs offline
import time
from concurrent.futures import ProcessPoolExecutor

def square(n):
    return n * n

def sum_squares(chunk):
    return sum(n * n for n in chunk)

if __name__ == "__main__":
    data = list(range(20_000))
    t = time.perf_counter(); serial = [square(n) for n in data]
    print(f"serial loop            {time.perf_counter()-t:6.3f} s")
    with ProcessPoolExecutor(4) as ex:
        ex.submit(square, 1).result()           # warm up the workers
        t = time.perf_counter(); r = list(ex.map(square, data))
        print(f"pool, 1 item per task  {time.perf_counter()-t:6.3f} s   (chunksize=1)")
        t = time.perf_counter(); r = list(ex.map(square, data, chunksize=500))
        print(f"pool, chunksize=500   {time.perf_counter()-t:6.3f} s")
    # genuinely heavy work per item
    def heavy(n): return sum(i * i for i in range(n))
    N = 2_000_000

Make the invisible visible: Run it.

output · Python 3.14runs offline
serial loop             0.001 s
pool, 1 item per task   2.210 s   (chunksize=1)
pool, chunksize=500    0.029 s
8 heavy jobs, serial    0.821 s
8 heavy jobs, 4 procs   0.240 s
# measured on the course machine (12 cores); your numbers will differ

What you see: The serial loop took 0.001 s. One item per task took about 2.2 s: roughly 110 microseconds of overhead per item, about 2,000 times slower. Chunks of 500 cut it to 0.029 s, still 20 times slower than serial, because the work per item is too small to ever pay back. The heavy jobs, 0.82 s each serial, finished in 0.24 s on 4 processes: 3.4x faster.

Naive: one item per task

Every call crosses the process boundary.

slow.pyruns offline
with ProcessPoolExecutor(4) as ex:
    out = list(ex.map(f, data))
# 20,000 round trips: 2.2 s

Better: big units of work

Ship a slice, return one number.

fast.pyruns offline
chunks = [data[i:i+500]
          for i in range(0, N, 500)]
out = list(ex.map(f_chunk, chunks))
# 40 round trips

The shift: Count round trips, not items: the unit sent to a process should cost at least milliseconds of CPU.

Why: Parallelism has a price per message. It only helps when the work per message is big compared with that price.

Land it I say a process pool pays a pickling and pipe cost per task, so I measure per-item overhead, chunk the work into large units, keep inputs and outputs small, and stop at one worker per real core.

Likely follow-ups
"How do I choose a chunk size?"

I aim for tasks that take about 10 to 100 ms of CPU. At that size the overhead of sending the task, which is perhaps 100 microseconds to a millisecond, is under a few percent. Longer tasks work but have two costs: the pool balances load worse (one long task at the end can leave other workers idle), and a failure loses more work.

The starting formula is chunksize = len(data) / (workers * 4). Four chunks per worker gives some room for balancing.

chunk size arithmetic (assumed numbers)runs offline
400,000 items, 4 workers: 400000 / (4 x 4) = 25,000 items per chunk
each item 4 us -> chunk = 100 ms of work, overhead about 1 percent

Then I measure with two or three sizes, one smaller and one larger, and keep the best. The right figure depends on the item cost, which I time in a single process first.

"What if the data is big, such as a large array?"

I avoid pickling it for every task, since a large array copied to each worker costs more than the computation. There are three ways:

  1. Shared memory: multiprocessing.shared_memory puts the array in one block that all workers map, so each reads the same bytes. A NumPy array can be a view on it, with no copy.
  2. A memory-mapped file: numpy.memmap or a file on disk, which the operating system caches once and shares across processes.
  3. Load once per worker: an initializer function loads the data when the worker starts, and tasks send only a row range, such as (1000, 2000).

The size of the saving: a 400 MB array sent as an argument to 1,000 tasks means 400 GB of pickling and copying. Sent as 1,000 pairs of integers, it is a few kilobytes.

With the shared-memory option, remember to treat the data as read-only, or give each worker its own slice to write, so no two processes write the same bytes.

"Does a pool start slowly?"

Yes, and for short jobs the start-up can be longer than the work. A worker process must be created, and under spawn or forkserver each one imports your modules before running its first task. With heavy imports, such as pandas or a machine-learning library, that can take hundreds of milliseconds or more per worker.

In the demo I submit a tiny job first, so the start-up is finished before the clock starts, and the timing shows only the steady-state cost. In a real script, that cost is part of the run.

Three practical points:

  1. Reuse the pool: create it once and send many tasks, instead of creating it in a loop.
  2. Keep imports small: workers should import only what the task needs.
  3. Do the arithmetic first: if the whole serial job takes 300 ms and worker start-up takes 200 ms, a pool cannot win.

For a long-running service the start-up is paid once and is not a concern.

"Why 3.4x on 4 processes and not 4x?"

Because of fixed costs, and because the idealised model of "4 workers, 4 times faster" ignores them. The serial version does the work only. The pool also starts workers, pickles each chunk's arguments and results, waits for the slowest worker to finish, and combines the results in the parent.

A simple model shows the effect. Suppose the work takes 4.0 s on one process, and the extra costs add 0.2 s in total. Four workers take 4.0 / 4 + 0.2 = 1.2 s, a speed-up of 4.0 / 1.2 = 3.3 times. Add uneven chunks, and 3.4 is a reasonable measured result, not a failure.

Other reasons are that the parent process needs a core of its own, that cores share memory bandwidth and caches, and that a part of the program is serial. By Amdahl's law, if 5 percent of the program cannot be parallelised, four workers can give at most about 3.5 times.

If the speed-up stops growing as I add workers, I look for the serial part or for a memory bandwidth limit.

Q96 · Scenario. "A forked worker deadlocks at start-up. Why?"

Reveal answer

Strong answer fork() copies the whole process but only the thread that called it. Every other thread simply does not exist in the child. If one of those threads was holding a lock at the instant of the fork, the child has a copy of that lock in the "locked" state, and the thread that would have unlocked it is gone. The first time the child needs that lock, it waits forever.

The locks do not have to be yours. Logging handlers, the memory allocator, the import system, a database or gRPC client, a metrics thread: any of them may hold an internal lock at the wrong moment. The result is a worker that hangs at start-up, with no error and no CPU use, and it happens only sometimes, which makes it hard to reproduce.

Python has defences for its own locks (the standard library re-initialises the logging and import locks after a fork), and since 3.12 it prints a DeprecationWarning when you fork a multi-threaded process. It cannot protect locks owned by your code or by C libraries.

The fixes: start worker processes before any threads exist; use spawn or forkserver (the 3.14 default on Linux); and reset library state in children with os.register_at_fork or by creating clients lazily inside the worker.

Picture it A background thread holds a lock while the main thread forks. The child then tries to take the same lock.

The setup: A thread takes lock and sleeps for a second. After 0.1 s the main thread forks. The child calls lock.acquire(). The parent waits up to 2 s for the child to finish.

fork_deadlock.py · Python 3.14runs offline
import os, threading, time, warnings
warnings.simplefilter("ignore")
lock = threading.Lock()

def holder():
    with lock:                     # another thread holds the lock at the moment of fork
        time.sleep(1.0)

threading.Thread(target=holder).start()
time.sleep(0.1)
pid = os.fork()
if pid == 0:                       # child: only the forking thread exists here
    lock.acquire()                 # nobody in the child will ever release it
    os._exit(0)
for _ in range(20):
    done, _status = os.waitpid(pid, os.WNOHANG)
    if done:
        print("child finished"); break
    time.sleep(0.1)
else:
    print("child still stuck after 2 s -> deadlock; killing it")
    os.kill(pid, 9); os.waitpid(pid, 0)

Make the invisible visible: Run it.

output · Python 3.14runs offline
child still stuck after 2 s -> deadlock; killing it

What you see: The child never finished. The lock was held by a thread that does not exist in the child, so nobody could ever release it. The parent had to kill the child.

Make the invisible visible: The warning Python 3.12 prints for the same mistake.

fork_thread_warning.py · Python 3.12runs offline
/home/iam100god/Desktop/AI_COURSE/code/e19-python-deep-dive/E/fork_thread_warning.py:4: DeprecationWarning: This process (pid=202158) is multi-threaded, use of fork() may lead to deadlocks in the child.
  pid = os.fork()                 # ❌ fork() while another thread is alive
parent: forked a child while a thread was running

What you see: Python warns: "This process is multi-threaded, use of fork() may lead to deadlocks in the child." Treat this warning as a bug report, not a notice.

what the child inheritsruns offline
# illustrative
parent: thread A (holds lock L)   thread B (calls fork)
fork() -------------------------------------------------
child : thread B only             lock L: still LOCKED
        thread A: does not exist  -> L can never be released
        child calls L.acquire()   -> waits forever

Fork a threaded process

Locks held by other threads stay locked.

risky.pyruns offline
threading.Thread(target=bg).start()
os.fork()    # child may hang on a lock

Fork first, or spawn

No other thread exists at fork time.

safe.pyruns offline
pool = ProcessPoolExecutor(4)   # first
threading.Thread(target=bg).start()

The shift: Order matters: processes before threads, or avoid fork altogether.

Why: fork copies memory, including the locked state of a lock, but not the threads that would unlock it.

Land it I explain that fork keeps only the calling thread, so any lock another thread held stays locked in the child forever, and I avoid it by forking before threads start or by using spawn or forkserver.

Likely follow-ups
"How do I diagnose a hung worker?"

I dump the stacks of the stuck process, because a deadlock leaves a precise trace of where each thread is waiting. The tool is py-spy dump --pid <pid>. It reads the process from outside, needs no change to the code, and shows every Python thread with its call stack.

  1. Find the stuck child: a worker with no CPU use and a state of sleeping, in top or ps.
  2. Dump it: a deadlocked child shows its main thread inside lock.acquire, _acquireLock in logging, or a similar wait.
  3. Read the lock's owner: if the stack shows a lock but no other thread exists in the child, that is the fork signature: the owner was in the parent.

In my own code I add faulthandler.dump_traceback_later(30) at worker start-up. If the worker is still stuck after 30 seconds, it prints its own stacks to stderr, so the evidence is in the logs without anyone logging in.

I then fix the cause (Q94) and keep the 30-second dump as a cheap alarm for future hangs.

"Does Python protect me from this for logging?"

Mostly yes, and the reason shows how the problem is handled in general. The standard logging module registers a function with os.register_at_fork that, in the child, re-creates the module's internal locks and each handler's lock. So the standard handlers, such as a stream or file handler, are safe after a fork.

It does not protect what it does not own. A custom handler that holds a network connection can be halfway through writing to its socket at the fork, so the child inherits a shared connection with a broken state. A third-party library, such as a metrics client or a database driver, has its own lock, and the standard library knows nothing about it.

So the protection is real but narrow. It covers Python's own locks, since the core developers could fix them, and it does not cover yours.

For my own code and libraries, I do one of three things: create the object after the fork, reset it with os.register_at_fork(after_in_child=...), or avoid forking a threaded process.

"What about gunicorn with --preload?"

Preloading imports the app once in the parent, then forks the workers. The benefit is memory: the loaded code and data are shared copy-on-write, and workers start quickly, since the imports are already done.

The danger is whatever the import started. A background thread, a connection pool, a metrics exporter or a scheduler that begins at import time exists only in the parent. The forked workers do not get the thread. They get a copy of its objects, perhaps with a held lock or an open connection shared with the parent, which is a deadlock or a data-corruption risk.

  1. Do not start threads at import: create them in a function that runs after the fork.
  2. Use the post-fork hook: in gunicorn, post_fork(server, worker), where each worker opens its own database connection and starts its own exporter.
  3. Close in the parent: connections opened during preload are closed or disposed before forking, so children do not inherit them.

Without preload, each worker imports its own copy, which is safer and uses more memory.

"Can I make fork safe by taking all locks before the fork?"

In principle yes, and os.register_at_fork exists for it. It takes three callbacks: before runs in the parent just before the fork, after_in_parent runs in the parent afterwards, and after_in_child runs in the child. The trick is to take a library's lock in before, so that no other thread can hold it at the instant of the fork, and release it in both of the other callbacks.

The standard library does this for its own locks. For my code it is a matter of order and risk. With several locks, I must take them in a fixed order, or the pre-fork step itself can deadlock. If a thread holds a lock for a long time, the fork waits for it. And I must be sure I know every lock the child will use, including those inside C libraries, where I cannot reach them.

One missed lock gives an intermittent hang that appears once a week in production. So my choice is not to fork a threaded process at all: start workers before threads, or use spawn or forkserver.

Q97. "What is concurrent.interpreters (3.14), and when is it useful?"

Reveal answer

Strong answer Since 3.12 each interpreter inside one process can have its own GIL and its own set of modules and objects (PEP 684). Python 3.14 adds the public API (PEP 734): concurrent.interpreters, plus InterpreterPoolExecutor in concurrent.futures.

Think of it as a lighter process: separate state like a process, inside the same process like a thread. Because each interpreter has its own GIL, several of them run Python code in parallel on several cores.

Nothing is shared by default. Objects cannot be passed between interpreters; data is copied, or passed through special shareable types such as the interpreter queue. That isolation is the point: there are no data races on Python objects.

It is useful when I want CPU parallelism with isolation and cheaper start-up than processes, and the free-threaded build is not an option. Caveats: the API is new, and a C extension must support being loaded in several interpreters, so not every library works.

Picture it Create a sub-interpreter, prove it is isolated, use the pool, and send a message through a queue.

The setup: interp.exec runs source code inside the new interpreter. The pool runs a function in four of them. A queue carries one message back.

interpreters_demo.py · Python 3.14runs offline
from concurrent import interpreters
from concurrent.futures import InterpreterPoolExecutor
import sys

interp = interpreters.create()
interp.exec("x = 41 + 1; print('inside sub-interpreter, x =', x)")
try:
    x
except NameError:
    print("main interpreter cannot see x: nothing is shared")

def work(n):
    return sum(i * i for i in range(n))

with InterpreterPoolExecutor(max_workers=4) as ex:
    print(list(ex.map(work, [1000, 2000, 3000, 4000])))

q = interpreters.create_queue()
interp.prepare_main(q=q)
interp.exec("q.put('hello from the other interpreter')")
print("received:", q.get())
interp.close()

Make the invisible visible: Run it.

output · Python 3.14runs offline
inside sub-interpreter, x = 42
main interpreter cannot see x: nothing is shared
[332833500, 2664667000, 8995500500, 21325334000]
received: hello from the other interpreter

What you see: The variable x exists inside the sub-interpreter but the main one raised NameError (so it printed the isolation message). The pool returned four results in input order, and the queue carried a string between interpreters.

Make the invisible visible: Does it give real parallel CPU speed-up? Four CPU jobs, same function on every executor.

interp_cpu.py · Python 3.14runs offline
import time
from concurrent.futures import InterpreterPoolExecutor, ProcessPoolExecutor, ThreadPoolExecutor

def work(n):
    total = 0
    for i in range(n):
        total += i * i % 7
    return total

N, JOBS = 3_000_000, 4

def timed(label, ex_cls):
    with ex_cls(JOBS) as ex:
        list(ex.map(work, [10] * JOBS))                 # warm up the workers
        t = time.perf_counter(); list(ex.map(work, [N] * JOBS))
        print(f"{label:22} {time.perf_counter() - t:5.2f} s")

if __name__ == "__main__":
    t = time.perf_counter(); [work(N) for _ in range(JOBS)]
    print(f"{'serial':22} {time.perf_counter() - t:5.2f} s")
    timed("4 threads", ThreadPoolExecutor)
    timed("4 subinterpreters", InterpreterPoolExecutor)
    timed("4 processes", ProcessPoolExecutor)
output · Python 3.14runs offline
serial                  0.78 s
4 threads               1.78 s
4 subinterpreters       0.19 s
4 processes             0.19 s
# measured on the course machine (12 cores); your numbers will differ

What you see: Threads were slower than serial (GIL contention). Sub-interpreters and processes both took 0.19 s, 4x faster than serial. Same speed here because the jobs are big; the difference would be start-up cost and memory.

Why: Each interpreter owns its GIL, so four interpreters can run Python at once, without the pickling-to-another-process machinery for shared state.

Land it I describe subinterpreters as isolated interpreters in one process, each with its own GIL, giving parallel CPU work without shared objects, and I would pick them over processes when start-up cost or memory matters and my libraries support them.

Likely follow-ups
"How is it different from the free-threaded build?"

They differ in what they remove. Free-threading removes the GIL and keeps one shared world, where all threads see the same objects. Subinterpreters keep the GIL but give each interpreter its own, and the interpreters share no Python objects.

That produces opposite trade-offs. With free-threading, sharing a large dictionary between 8 workers costs nothing, but you must make the code race-free, since two threads can change an object at once. With interpreters, a race on Python objects is impossible by construction, but the dictionary has to be copied into each interpreter, or sent through shareable types.

QuestionFree-threaded 3.14tconcurrent.interpreters
Objects shared?Yes, allNo
Data races possible?Yes, in your codeNo, between interpreters
BuildSeparate buildNormal build
Extension supportNeeds free-threading flagNeeds multi-interpreter support

I choose interpreters for independent jobs, and free-threading for shared data.

"How is it different from multiprocessing?"

The isolation is the same as processes, but everything runs inside one operating-system process. That gives three differences.

  1. Cost: creating an interpreter is cheaper than starting a process, and the memory overhead is lower, since the process-level resources are shared.
  2. Failure: a crash in C code, such as a segmentation fault in an extension, takes down the whole process and every interpreter in it. With processes, only the worker dies, and the parent can start another.
  3. Control: I can terminate a stuck process from outside, and I cannot easily kill an interpreter that is stuck in a loop.

So processes remain the stronger isolation: full memory separation, a kill switch and crash containment. Interpreters are a lighter version for code I trust.

A rule of thumb: for untrusted or crash-prone native code, use processes. For many small, trusted, CPU-bound jobs where start-up cost and memory matter, benchmark interpreters against processes before choosing.

"How do I pass data in and out?"

There are three routes, and each has a limit on what it accepts.

The first is the arguments and results of the pool, such as InterpreterPoolExecutor. These are copied, using pickle-style serialisation, so any picklable value works, and the cost grows with its size.

The second is a queue for streaming. interpreters.create_queue() gives a queue that is usable from several interpreters, and it accepts shareable values: numbers, strings, bytes, None, tuples of such values, and a few more. A dict or an ordinary class instance is not shareable and must be converted first.

The third is a buffer. An object that supports the buffer protocol, such as bytes or a memoryview, can share its memory without a copy, which is the way to hand over a large block of numbers.

My design choice follows from this: I send small messages and keep large data in a shared buffer or a file, as I would with processes (Q98). The exact list of shareable types should be checked in the 3.14 documentation.

"Is it production-ready?"

I would say it is new, with a clear plan for how to use it. The API arrived in 3.14, which is a year old at this point, and the ecosystem is still catching up. The risk is mostly in extensions: a compiled library must declare that it can be loaded in several interpreters, and many have not yet done so.

My plan for a trial has four parts:

  1. Scope: a pure-Python or well-tested workload, such as CPU-bound parsing, where I control the dependencies.
  2. Benchmark: compare it with a process pool on the same job, for speed and memory. If interpreters are only 10 percent better, the benefit may not justify the risk.
  3. Fallback: keep the process pool code path behind a setting, so I can switch back at once.
  4. Read the notes: check the 3.14 and 3.15 What's New pages for changes, since a young API still moves.

I would not make it a hard dependency of a critical path before it has run in production somewhere I can measure.

Q98. "How do you share data between processes safely, and what does each option cost?"

Reveal answer

Strong answer Processes do not share memory by default, so every option is a trade between convenience, speed and risk.

Pass messages with multiprocessing.Queue or Pipe: values are pickled and copied. Simple and safe, moderate cost. Manager objects (m.dict()) give you a shared dict or list through a proxy: easy to use, but every operation is a round trip to a server process, so it is very slow. Value and Array give a small shared C value with a lock. shared_memory gives a raw block of bytes mapped into several processes: the fastest, but you manage layout and synchronisation yourself.

Outside Python: a file or memory-mapped file, a database, Redis, a message queue. For anything that must survive a crash or span machines, those are the right answer anyway.

My rule: send work in and results out through queues, keep workers independent, and use shared memory only for large read-mostly arrays, with one writer.

Picture it The cost of each option for 5,000 simple operations, measured.

The setup: Plain dict, a Manager().dict() proxy, mp.Queue put and get, and a write into shared_memory.

shared_cost.py · Python 3.14runs offline
import multiprocessing as mp, time

def timed(label, f):
    t = time.perf_counter(); f(); print(f"{label:32} {(time.perf_counter() - t) / 5000 * 1e6:9.2f} us per operation")

def plain():
    d = {}
    for i in range(5000): d[i] = i

def via_manager(d):
    for i in range(5000): d[i] = i

def via_queue(q):
    for i in range(5000): q.put(i)
    for i in range(5000): q.get()

if __name__ == "__main__":
    timed("plain dict", plain)
    with mp.Manager() as m:
        d = m.dict(); timed("Manager().dict() (proxy)", lambda: via_manager(d))
    q = mp.Queue(); timed("mp.Queue put+get (pickled)", lambda: via_queue(q))
    from multiprocessing import shared_memory
    shm = shared_memory.SharedMemory(create=True, size=8192); b = shm.buf
    def raw():
        for i in range(5000): b[i % 8000] = i % 256
    timed("shared_memory byte write", raw)
    b.release(); shm.close(); shm.unlink()

Make the invisible visible: Run it.

output · Python 3.14runs offline
plain dict                            0.10 us per operation
Manager().dict() (proxy)             76.60 us per operation
mp.Queue put+get (pickled)           18.28 us per operation
shared_memory byte write              0.07 us per operation
# measured on the course machine; your numbers will differ

What you see: A plain dict operation costs 0.1 microseconds. The manager proxy cost 77 microseconds, about 770 times more. A queue put and get cost 18 microseconds. A raw shared-memory byte write cost 0.07 microseconds: as cheap as local memory.

Make the invisible visible: A child writing into shared memory, and a lock-protected counter across four processes.

shared_memory_demo.py · Python 3.14runs offline
parent sees byte 0 = 99 (changed by the child, no copy)
queue (pickled): {'sku': 'A1', 'qty': 2}
Value with lock, 4 procs x 1000 = 4000

Why: Shared memory is fast because nothing is copied, and dangerous for the same reason: two writers need a lock, and Python will not add one for you.

Land it I prefer message passing through queues, accept the pickling cost, avoid Manager proxies for hot paths, and use shared_memory only for big read-mostly buffers with a clear owner.

Likely follow-ups
"When is a Manager a good idea?"

A Manager is good for small amounts of coordination data that change rarely, and when convenience matters more than speed. A progress dictionary that workers update a few times per second is a fair example. The other case is when the processes run on different machines, since a manager can be reached over the network.

Why it is slow: m.dict() is not shared memory. It is a proxy object. Every read or write is sent to a separate server process, which does the operation and replies. In the chapter's measurement that round trip took about 77 microseconds.

round-trip arithmetic (using the measured 77 us)runs offline
1,000,000 updates x 77 us = 77 s
(an ordinary dict update is about 0.05 us)

So a hot loop of a million updates would spend over a minute just talking to the manager. For that case I use local counters in each worker and send the totals at the end, or put results on a queue in batches.

"What is the safe way to use shared_memory?"

The safest rule is one writer per block, and a clear owner. If several processes must write, protect the writes with a lock or a semaphore from multiprocessing, because shared memory has no protection of its own: two processes can overwrite each other's bytes without any error.

  1. Fixed layout: store data of a fixed size and type. A NumPy array that views the buffer works well, since its shape and dtype are known to both sides.
  2. Disjoint writes: give each worker its own slice, such as rows 0 to 999 for worker 1, so no lock is needed.
  3. Clean up once: the creator calls close() in every process and unlink() exactly once, in the owner.

The last point is easy to miss. If unlink() never runs, the block stays in the system until reboot (on Linux it lives under /dev/shm), and a crash in the middle leaves a leak. I wrap creation and unlink in try/finally.

I also remember that a shared array has no safe way to grow, so I size it up front.

"Why does a Value need get_lock()?"

Because v.value += 1 is not one operation. It reads the number, adds one, and writes it back, which is the same race as counter += 1 in Q78. Two processes can both read 5 and both write 6, losing one update. Processes do not even have a GIL in common to narrow the window.

Value includes a lock, which you get through v.get_lock(), but it does not apply the lock to your code for you. You must take it around the whole read-modify-write:

value update patternruns offline
with v.get_lock():
    v.value += 1

The reason the lock is separate is flexibility. For a flag that one process writes and others read, no lock is needed. For a counter, you need one. Using Value('i', 0, lock=False) gives no lock at all, which is only right for a single writer.

As the demo above does, I keep the locked section tiny, and I prefer per-process counters merged at the end when speed matters.

"What about passing a huge object to many workers?"

I send a reference, not the data. A file path, an object key in storage, or a row range such as (10000, 20000) is a few bytes, and each worker loads only its own slice. Pickling a 500 MB object once per task would cost seconds each time, and it would put 8 copies in memory with 8 workers.

There are three patterns, depending on the data:

  1. Load in the worker: an initializer function reads the data once when the worker starts, into a global, and tasks use it.
  2. Shared buffer: shared_memory or a memory-mapped file for large arrays, so workers read the same bytes (Q95).
  3. Fork's copy-on-write: a read-only structure loaded before the fork is shared without copying. It only works under fork, with the caveats of Q94: reference counting makes pages copy gradually, and a threaded parent is dangerous.

I choose by who owns the data and how often it changes. Read-only and large suits memory mapping. Small and changing suits messages. Anything that must survive a crash belongs in a database, not in a process.

Q99. "Which threading primitives do you actually use, and what is queue.Queue for?"

Reveal answer

Strong answer Five cover almost everything. Lock: only one thread at a time inside a critical section, always used as with lock:. Event: a flag threads can wait on and one thread can set; the standard way to say "stop". Semaphore: allow N at a time. Condition: wait until some state becomes true; rarely written by hand. RLock: a lock the same thread can take again; I avoid it because it hides design problems.

queue.Queue is the one I use most. It is a thread-safe FIFO queue with blocking put and get. Producers call put, workers call get, and the queue does all the locking. A maxsize makes put block when full, which gives backpressure. task_done and join let the producer wait until all items are processed.

The pattern is: put work in the queue, start N worker threads that loop on get, and stop them by putting one sentinel value per worker.

The guiding idea is to share data by passing it through a queue, not by sharing variables guarded by many locks.

Picture it A bounded queue, three workers, a sentinel to stop them.

The setup: Ten numbers go into a queue of size 5 (so the producer sometimes waits). Three workers square them and put results on another queue.

queue_workers.py · Python 3.14runs offline
import queue, threading

jobs = queue.Queue(maxsize=5)          # bounded: put() blocks when full
results = queue.Queue()
STOP = object()

def worker():
    while (item := jobs.get()) is not STOP:
        results.put((threading.current_thread().name, item * item))
        jobs.task_done()
    jobs.task_done()

threads = [threading.Thread(target=worker, name=f"w{i}") for i in range(3)]
[t.start() for t in threads]
for n in range(10):
    jobs.put(n)
for _ in threads:
    jobs.put(STOP)
jobs.join()
print(sorted(r[1] for r in list(results.queue)))

Make the invisible visible: Run it.

output · Python 3.14runs offline
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

What you see: All ten squares arrived. The producer was slowed by the bounded queue, and each worker exited when it received the STOP sentinel, so join returned.

Hand-made sharing

A list and a lock around every access. Easy to forget a lock somewhere.

shared.pyruns offline
items = []
lock = threading.Lock()
def add(x):
    with lock:
        items.append(x)
# and workers must poll...

queue.Queue

The queue owns the lock and the waiting.

queued.pyruns offline
q = queue.Queue(maxsize=5)
q.put(x)      # blocks if full
item = q.get()  # blocks if empty

The shift: Stop sharing variables; hand over items through a queue, and let it do the locking and the blocking.

Why: A worker blocked in get() uses no CPU and wakes the moment work arrives. Polling a list with sleep wastes time and adds delay.

Land it I use Lock with a with-statement, Event for stop signals, Semaphore for limits, and above all queue.Queue to pass work between threads, because the queue does the locking and gives backpressure.

Likely follow-ups
"Queue, deque, multiprocessing.Queue, asyncio.Queue — which is which?"

Four queues, four jobs, and mixing them is a common source of bugs.

  1. queue.Queue: for threads. It has blocking put and get, a size limit, and task_done and join.
  2. collections.deque: a fast double-ended list whose append and popleft are atomic in CPython, but they never block. A consumer must poll, which wastes CPU or adds delay.
  3. multiprocessing.Queue: crosses process boundaries. Items are pickled and sent through a pipe, so they must be picklable and are copied.
  4. asyncio.Queue: for coroutines on one event loop, with await put and await get. It is not thread-safe.

The last point is the trap. If a worker thread calls put_nowait on an asyncio.Queue, the loop may never wake up, or the queue's internal state may be damaged. The correct call from a thread is loop.call_soon_threadsafe(queue.put_nowait, item).

My rule is to pick the queue by what is on each side: threads, processes or coroutines.

"Why a sentinel instead of checking q.empty()?"

Because q.empty() is a snapshot that is already out of date when you read it. Another thread may put an item a microsecond later. A worker that exits when the queue looks empty can leave work behind, or two workers can both see "not empty" and both call get() for the single remaining item, and one blocks forever.

A sentinel is an explicit message: "there is no more work". It travels through the same queue, in order, so it arrives after every real item. The worker sees it and stops, with no timing assumption at all.

The details I keep in mind:

  1. One sentinel per worker: a worker that consumes the sentinel does not pass it on, so with 4 workers, the producer puts 4 of them.
  2. Put them last: only after the final real item is in the queue.
  3. Use an unmistakable value: None or a dedicated object(), never a value that real work could contain.

If the work is open-ended, I use an Event as a stop flag instead.

"When do I need task_done and join?"

When the producer must know that all items have been fully processed, not merely taken from the queue. get() only removes an item. It says nothing about whether the worker finished with it. A queue can be empty while the last item is still being processed.

The mechanism is a counter. Each put adds one to the count of unfinished tasks, and each task_done() subtracts one. q.join() blocks until the count reaches zero.

The rules:

  1. One task_done per get: call it after the work is finished, ideally in a finally so a failure does not skip it.
  2. Call join in the producer: it returns when everything put has been processed.
  3. Never over-call: an extra task_done raises ValueError.

The trap is the opposite one. A missing task_done, for example when an exception is raised in the worker before it, leaves the count above zero, and join hangs forever. A hang at the end of a batch job is often exactly this.

"Does Lock still matter on the free-threaded build?"

More than before. On the normal build, the GIL makes many races rare, and sloppy code often seems to work. On 3.14t, threads really do run at the same time, so shared mutable data needs real locks. The chapter's counter test lost about 2.9 million of 4 million updates there without one (Q78).

The built-in containers keep their own internal consistency: append, d[k] = v and set.add do not corrupt memory. What was never protected, in either build, is a multi-step rule of yours. "Check that the key is absent, then insert it" is two steps, and another thread can run between them.

So the meaning of Lock does not change. What changes is how soon a missing lock shows. The habits that help are the same as before: keep shared state small, hold locks for a short time, never hold one across I/O, and prefer passing data through a queue.

When I plan a move to free-threading, I review every place that shares data and give it an owner.

Q100 · Scenario. "A thread pool of 200 workers for database calls made things slower. Why?"

Reveal answer

Strong answer Because the database can only do so much at once, and the extra threads just queue in front of it. Throughput is limited by the database's real capacity, a number tied to its CPU cores, disks and lock contention, not by how many threads ask. Beyond that number, more threads add waiting, memory, context switching and contention, but no extra answers.

Look at what 200 workers do. They open up to 200 connections (or fight over a smaller connection pool and time out waiting for one). The database server runs 200 concurrent queries, each slower because they compete for CPU, cache and locks. Latency rises, timeouts trigger retries, retries add load: a spiral.

A common rule of thumb for a relational database is a pool of roughly cores x 2 plus a few for disk wait, in the low tens even for a big server, and then to queue in the application with a timeout so overload becomes a fast, clear error instead of a slow one.

So I size the pool to the database, put a bounded queue in front, measure p99 as well as throughput, and use a connection pooler such as PgBouncer when many app instances share one database.

Picture it A simulated database that serves 8 queries at a time, 20 ms each, hit by 800 queries from 8, 32 and 200 threads.

The setup: A bounded semaphore of size 8 stands for the database's real capacity. Each worker waits for a slot, then "queries" for 20 ms.

db_pool_size.py · Python 3.14runs offline
import threading, time, statistics
from concurrent.futures import ThreadPoolExecutor

DB_CONNECTIONS = 8                      # what the database really serves at once
db = threading.BoundedSemaphore(DB_CONNECTIONS)

def query(_):
    t0 = time.perf_counter()
    with db:                            # the DB admits 8 at a time
        time.sleep(0.02)                # 20 ms of real database work
    return time.perf_counter() - t0

for workers in (8, 32, 200):
    t0 = time.perf_counter()
    with ThreadPoolExecutor(workers) as ex:
        lat = sorted(ex.map(query, range(800)))
    total = time.perf_counter() - t0
    print(f"{workers:3} workers: {800/total:5.0f} queries/s   "
          f"median latency {statistics.median(lat)*1000:5.0f} ms   p99 {lat[int(.99*len(lat))]*1000:5.0f} ms")

Make the invisible visible: Run it.

output · Python 3.14runs offline
  8 workers:   394 queries/s   median latency    20 ms   p99    21 ms
 32 workers:   394 queries/s   median latency    20 ms   p99  2018 ms
200 workers:   391 queries/s   median latency    20 ms   p99  2025 ms
# measured on the course machine; your numbers will differ

What you see: Throughput stayed at about 395 queries per second whether I used 8, 32 or 200 workers. That equals 8 slots / 0.02 s = 400 per second: the capacity of the database. The p99 latency, however, went from 21 ms to over 2 s. Extra workers did not add speed, they added tail latency.

Why: The median looks fine because most threads are served quickly; the unlucky ones, woken late by an unfair queue, wait seconds. That is the signature of overload: the average hides the tail. The numbers here are a model of a database, not a real one, but the shape is the same as in production incidents.

Land it I explain that throughput is capped by the database, so more threads only lengthen the queue, and I size the pool near the database's capacity, bound the queue with a timeout, and watch p99 rather than the average.

Likely follow-ups
"How do I find the right pool size?"

I measure it, because the right number depends on the database's hardware, the kind of queries and the amount of lock contention. A formula only gives a starting point.

  1. Start from the rule of thumb: around 2 times the database's cores, plus a few for disk waits. For an 8-core server, about 20 connections in total.
  2. Run a load test at several sizes: for example 5, 10, 20, 40, 80, with realistic queries. Record throughput and p99 latency at each.
  3. Stop where the curve flattens: throughput stops rising at some size, while latency keeps climbing. The pool should be near that knee, not past it.

While I raise the size, I watch the database side: CPU, lock waits, active queries and the buffer cache. If CPU is near 100 percent, adding connections cannot help.

The answer for production is usually smaller than people expect, often 10 to 30 connections per database, and the extra traffic waits in a bounded queue in the application. A small pool with a short queue is faster than a large pool.

"Does asyncio change this?"

No, not for this problem. An async driver lets one thread hold thousands of waiting requests cheaply, and that removes the thread cost. It does not add capacity to the database. The server can still run only so many queries at once, whatever the client looks like.

If anything, asyncio makes the mistake easier. Creating 5,000 tasks that all query is trivial, and with no limit, 5,000 queries reach the database together. The cure is the same: cap the number of in-flight queries.

  1. Use the driver's pool size: for example, a maximum of 20 connections. Further requests wait for a connection.
  2. Or add a semaphore: asyncio.Semaphore(20) around the query, as in Q87, which also covers calls that do not use the pool.
  3. Add a timeout: on the wait for a slot, so overload becomes a quick error.

What asyncio does give is memory. 5,000 waiting requests cost kilobytes each, not 5,000 threads.

"What about many app instances?"

The total is what the database sees, so I multiply. Twenty instances, each with a pool of 20, make 400 connections. Many databases handle that badly. PostgreSQL, for example, uses one server process per connection, and several hundred active ones waste memory and CPU on switching, and the limit max_connections is often set to 100 by default.

There are two fixes, and they can be combined:

  1. Shrink each pool: divide the database's budget by the number of instances. With a budget of 60 and 20 instances, each gets 3. Autoscaling changes the instance count, so the budget must include the maximum.
  2. Add a pooler: PgBouncer in transaction mode sits between the apps and the database and lets thousands of client connections share a few dozen real ones.

A pooler in transaction mode has restrictions. Session features such as session-level prepared statements, advisory locks and SET may not work, since two transactions of one client can run on different server connections. I check my driver's settings before I turn it on.

"What should happen when the pool is exhausted?"

It should fail fast, and say so clearly. I give pool acquisition a short timeout, a second or two, and when it expires I return an error (a 503 with a retry hint) or drop the optional work.

The alternative looks gentler and is worse. If a request waits 30 seconds for a connection, it holds a worker thread (or an open client connection) and memory for 30 seconds. With 200 threads all waiting, the application has no thread left for requests that do not need the database, such as health checks. Then the load balancer marks it unhealthy. A database slowdown has become a full outage.

Failing quickly has two effects. It frees the resource at once, so the application keeps serving what it can. And it gives the caller a signal to back off, where a long wait gives no signal until it is too late.

I pair this with a metric on pool wait time, and an alert when it rises, so I see the saturation before the errors begin.

Q101. "concurrent.futures versus Java's ExecutorService."

Reveal answer

Strong answer They solve the same problem: submit work to a pool, get a handle (a Future) back, and collect the result later. The shapes are almost the same, so a Java engineer can read Python's version in a minute.

ThreadPoolExecutor and ProcessPoolExecutor (and InterpreterPoolExecutor in 3.14) share one interface: submit(fn, *args) returns a Future; future.result() blocks and returns the value or re-raises; map returns results in input order; as_completed yields futures as they finish; a with block calls shutdown(wait=True).

Differences worth knowing. Exceptions: Python's result() re-raises the original exception, while Java's get() wraps it in an ExecutionException. One interface, three engines: switching threads to processes is a one-word change, as long as arguments pickle. No invokeAll: use map or as_completed. Composition: Java's CompletableFuture chains stages; in Python, composition is what asyncio is for.

Pool sizes: Python's default thread pool is min(32, cpu + 4); Java's fixed pool is whatever you pass.

Picture it Submit three jobs that finish in reverse order, one of which fails, and read them two ways.

Java · ExecutorService

Submit, block on get, shut down by hand.

Calc.javaruns offline
var pool = Executors
    .newFixedThreadPool(8);
Future<Integer> f =
    pool.submit(() -> calc(5));
int v = f.get(); // may throw
pool.shutdown();

Python · concurrent.futures

Same idea; the with block does the shutdown.

calc.pyruns offline
with ThreadPoolExecutor(8) as pool:
    f = pool.submit(calc, 5)
    v = f.result()  # may raise
# shutdown(wait=True) ran here

The shift: Same pool-and-future model; Python re-raises the original error, and the with-block replaces the shutdown call.

futures_demo.py · Python 3.14runs offline
from concurrent.futures import ThreadPoolExecutor, as_completed
import time

def calc(n):
    time.sleep(0.3 - n * 0.1)          # later items finish first
    if n == 2:
        raise ValueError("bad input 2")
    return n * n

with ThreadPoolExecutor(3) as pool:
    futs = {pool.submit(calc, n): n for n in range(3)}
    for f in as_completed(futs):                       # completion order
        n = futs[f]
        try:
            print(f"n={n} -> {f.result()}")
        except ValueError as e:
            print(f"n={n} raised {type(e).__name__}: {e}   (the original exception, not wrapped)")
    print("map keeps input order:", list(pool.map(lambda n: n + 100, range(3))))
# leaving the with-block called shutdown(wait=True)

Make the invisible visible: Run it. Job 2 finishes first and fails; job 0 finishes last.

output · Python 3.14runs offline
n=2 raised ValueError: bad input 2   (the original exception, not wrapped)
n=1 -> 1
n=0 -> 0
map keeps input order: [100, 101, 102]

What you see: as_completed gave completion order (2, 1, 0) and the failed job raised its own ValueError from result(). map returned input order. In Java the same failure would arrive as ExecutionException with the real error as its cause.

Land it I say futures work like ExecutorService: submit returns a Future, result re-raises the original error, as_completed gives completion order, and the same interface covers threads, processes and interpreters.

Likely follow-ups
"Where is invokeAll and invokeAny?"

Both exist, under other names, as small recipes. invokeAll means run every task and wait: list(pool.map(fn, items)) returns results in input order, and wait(futures) returns the finished and unfinished sets.

invokeAny means take the first success and cancel the rest. In Python I write next(as_completed(futs)), which hands me whichever future finishes first. One catch: as_completed also yields futures that failed, so for a true first-success I loop and skip any whose exception() is not None.

The cancelling half is weaker than in Java. cancel() only stops jobs still waiting in the queue. The run below has three workers, so all three jobs had already started and none could be cancelled.

q101_invokeany.py outputruns offline
first finished: fast
cancelled flags: [False, False, False]

I use this for hedged requests (ask two replicas, take the first answer) and make the slow jobs watch a stop flag so they end early.

"Can I cancel a running future?"

No. future.cancel() works only while the job is still waiting in the pool's queue. Once a worker has picked it up, cancel() returns False and the job runs to its end.

The reason is that Python has no safe way to stop a thread from outside. There is no equivalent of Java's cancel(true), which sends an interrupt that blocked calls such as sleep notice. Python's cancel behaves like Java's cancel(false). Killing a thread by force could leave a lock held or a file half-written, so the language does not offer it.

What I do instead is cooperative. I give each job a threading.Event named stop, and the job checks stop.is_set() between steps or waits with stop.wait(timeout). For many queued jobs, shutdown(wait=True, cancel_futures=True) drops everything that has not started.

If the work truly must be killable, I put it in a separate process, which can be terminated, and accept that its in-progress state is lost.

"What does add_done_callback do?"

It registers a function that is called with the future as its only argument once the future is finished, whether it succeeded, failed or was cancelled. Three details matter.

  1. Which thread: the callback runs in the worker thread that finished the job. If the future is already done when you add the callback, it runs at once in the thread that called add_done_callback.
  2. Errors: inside the callback you must call fut.result() or fut.exception() yourself. An exception raised by the callback itself is logged and swallowed, and nobody is told.
  3. Order: several callbacks on one future run in the order they were added.

Because it runs on a worker, a slow callback holds that worker and delays the next job. I keep it tiny, such as putting the result on a queue or bumping a counter under a lock. It is a small thenAccept, not a chain; for real composition I use asyncio.

"How do futures meet asyncio?"

Through two bridges. loop.run_in_executor(pool, fn, *args) submits to a concurrent.futures pool and returns an asyncio future you can await. asyncio.wrap_future(cf) does the same conversion for a future you already hold.

Underneath, the worker thread finishes the concurrent future, and a callback uses loop.call_soon_threadsafe to set the result on the asyncio future from the loop's own thread. That hand-off matters, because asyncio objects are not thread-safe and must only be touched from the loop thread.

asyncio.to_thread(fn, ...) is the short form. It uses the loop's default executor and also copies the current context variables into the worker. That default executor has at most min(32, cpu + 4) threads, which is 16 on this 12-core machine.

For CPU work I pass a ProcessPoolExecutor to run_in_executor, since the default thread pool would not run Python code in parallel. And I never call cf.result() inside a coroutine, because that blocks the whole loop.

Q102 · Scenario. "Ctrl+C does not stop your threaded program. Why, and how do you shut down cleanly?"

Reveal answer

Strong answer Ctrl+C sends SIGINT, which Python turns into a KeyboardInterrupt raised in the main thread only. Worker threads are not told. When the main thread ends, Python waits for every non-daemon thread to finish before exiting. A worker in an endless while True loop never finishes, so the program hangs after the main thread is done.

Setting daemon=True makes the exit immediate, but it kills the thread abruptly, in the middle of a write or a transaction. That is acceptable for disposable helpers only.

The clean pattern: one threading.Event named stop. Workers loop while not stop.is_set() and wait with stop.wait(timeout) or queue.get(timeout=...) so they wake up regularly. The main thread catches KeyboardInterrupt (and handles SIGTERM, which is what Kubernetes and systemd send), sets the event, then joins the workers with a timeout.

Never block forever in a call that cannot be woken: use timeouts on queue gets and socket reads.

Picture it The broken version and the fixed version, both really run.

The setup: sigint_bad.py: a non-daemon worker that never checks anything, killed by the run limit after 2 s. sigint_threads.py: an Event, with a timer that simulates Ctrl+C after 0.3 s.

sigint_bad.py · Python 3.14runs offline
import threading, time
def worker():
    while True:
        time.sleep(0.1)                 # never checks any flag
t = threading.Thread(target=worker)    # non-daemon
t.start()
print("main thread finished its work; interpreter now waits for the worker...")
output · Python 3.14 (run under timeout 2; exit code 124 means it was killed)runs offline
main thread finished its work; interpreter now waits for the worker...

What you see: The main thread finished at once, but the process did not exit: the interpreter waits for the worker.

sigint_threads.py · Python 3.14runs offline
import os, signal, threading, time

stop = threading.Event()

def worker(daemon_free):
    while not stop.is_set():
        stop.wait(0.1)                  # wakes at once when stop is set
    print("  worker: saw stop, finishing current job and exiting")

t = threading.Thread(target=worker, args=(True,)); t.start()
# simulate Ctrl+C after 0.3 s
threading.Timer(0.3, lambda: os.kill(os.getpid(), signal.SIGINT)).start()
try:
    while t.is_alive():
        t.join(timeout=0.2)             # join with a timeout so the main thread can see KeyboardInterrupt
except KeyboardInterrupt:
    print("main: KeyboardInterrupt, asking workers to stop")
    stop.set()
    t.join()
print("clean exit")
output · Python 3.14runs offline
main: KeyboardInterrupt, asking workers to stop
  worker: saw stop, finishing current job and exiting
clean exit

What you see now: The main thread saw KeyboardInterrupt, set the event, the worker noticed within 0.1 s and returned, and the process exited normally.

Daemon thread: dies abruptly

Exit is quick; work may be cut mid-write.

daemon.pyruns offline
t = Thread(target=loop, daemon=True)
t.start()
# process exits; loop is killed

Event: asked to stop

The worker finishes its job and returns.

event.pyruns offline
while not stop.is_set():
    do_one_job()
    stop.wait(0.1)
# main: stop.set(); t.join()

The shift: A daemon thread is stopped for you; an Event lets the worker stop itself cleanly.

Why: Threads cannot be killed from outside in Python. The only safe stop is a request the thread chooses to honour, so every loop needs a way to hear it.

Land it I explain that KeyboardInterrupt reaches only the main thread and non-daemon threads keep the process alive, so I use an Event for stop, wake workers with timeouts, handle SIGTERM too, and join cleanly.

Likely follow-ups
"Why join(timeout=0.2) in a loop?"

The loop lets the main thread return to Python code every 0.2 seconds, so signals are handled promptly and I control the shutdown deadline. Signal handlers run in the main thread, between bytecode steps. A long wait that cannot be interrupted would delay them.

On Linux a plain join() is also woken by signals in modern Python, so the loop is not strictly needed for that. I keep it for two other reasons: I can log progress ("2 workers still running") and I can enforce one total deadline instead of a timeout per thread.

shutdown with a deadlineruns offline
deadline = time.monotonic() + 10          # total budget: 10 s
for t in workers:
    while t.is_alive() and time.monotonic() < deadline:
        t.join(timeout=0.2)
stuck = [t.name for t in workers if t.is_alive()]
if stuck:
    log.error("did not stop in time: %s", stuck)

After the deadline I log which threads are stuck and exit anyway; that is better than hanging until the orchestrator sends SIGKILL.

"What about SIGTERM in containers?"

An orchestrator stops a container in two stages. It sends SIGTERM, waits a grace period (30 seconds by default in Kubernetes, set by terminationGracePeriodSeconds), then sends SIGKILL, which cannot be caught.

Python's default for SIGTERM is the operating-system default: the process is ended at once, with no finally blocks and no atexit handlers. In-flight work is lost mid-step. Ctrl+C is different, because Python converts SIGINT into KeyboardInterrupt, but SIGTERM gets no such treatment.

sigterm sets the same stop eventruns offline
def on_term(signum, frame):
    stop.set()                    # same Event the workers watch

signal.signal(signal.SIGTERM, on_term)

I keep the handler tiny, only setting the event, and do the real draining in the main flow. Then I size the work so that draining plus joining fits well inside the grace period, say 20 seconds of a 30 second budget.

"And for a ThreadPoolExecutor?"

Executor workers are joined when the interpreter exits, so one job that never returns keeps the process alive even after main is done. A plain shutdown() also waits for every queued job, which can mean minutes.

  1. Make jobs stoppable: pass each job the shared stop event and have it check between units of work, or use queue.get(timeout=...) inside the job.
  2. Drop what has not started: call pool.shutdown(wait=True, cancel_futures=True). Queued futures are cancelled; jobs already running are left to finish.
  3. Bound the wait: because running jobs cannot be forced to stop, I set stop first, then shut down, so they end within one loop turn.

The with block alone is not enough: it calls shutdown(wait=True) and will happily wait for a stuck job. If a job can truly hang, I run it in a process I can terminate.

"What is the asyncio equivalent?"

The ideas are the same, but the mechanics differ. Since Python 3.11, asyncio.run installs its own SIGINT handler. On Ctrl+C it cancels the main task, which raises CancelledError inside it and inside every task it awaits, so finally blocks and async with exits run. Afterwards KeyboardInterrupt is raised from asyncio.run.

A task that catches CancelledError and carries on, or that sits in blocking code, ignores the cancel. That is the usual reason an asyncio program "will not stop" (Q85).

For servers I do not rely on Ctrl+C. I register loop.add_signal_handler(signal.SIGTERM, stop.set) and have the main coroutine await stop.wait(). When it wakes, it stops accepting new work, waits for in-flight requests with a timeout (asyncio.timeout), and then returns.

Frameworks such as uvicorn already do this for you; I only write it myself for custom workers and consumers.

Q103 · Design. "Design CPU-heavy thumbnail generation for one million images a day on 16-core machines."

Reveal answer

Strong answer Start with the numbers. One million a day is 1,000,000 / 86,400 = 11.6 images per second on average. Traffic is bursty, so I plan for a peak of about 10x, around 116 per second. I then measure what one image costs, because the whole design follows from it.

On this machine, one 4000x3000 JPEG took about 66 ms using Pillow with JPEG draft mode, so one core handles about 15 images per second. Twelve processes took 9.5 ms per image wall-clock, a 6.9x speed-up, so a 16-core machine handles roughly 100 per second. Peak needs 116, so I run two machines, which also gives redundancy, and autoscale on queue depth.

Architecture: uploads put an object key on a durable queue (SQS, or Kafka as in Chapter E17). A worker pool, one process per core, takes a key, downloads the image, makes the sizes, uploads them under a deterministic key such as {hash}/{size}.jpg, and acknowledges. Because the output key is deterministic, a retry just overwrites: the job is idempotent.

Safety: cap image dimensions (Image.MAX_IMAGE_PIXELS) against decompression bombs, send corrupt files to a dead-letter queue after 3 tries, and limit memory (a decoded 12-megapixel image is about 36 MB per worker).

Picture it Measure one image, then 12 workers as processes and as threads.

The setup: A synthetic 4000x3000 JPEG (7.4 MB). thumb uses draft to let the JPEG decoder shrink the image while decoding, then resizes to 256 px.

thumbs.py · Python 3.12 (venv)runs offline
import io, time, os
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
from PIL import Image

def make_jpeg():
    img = Image.effect_noise((4000, 3000), 60).convert("RGB")
    buf = io.BytesIO(); img.save(buf, "JPEG", quality=85); return buf.getvalue()

def thumb(data):
    im = Image.open(io.BytesIO(data)); im.draft("RGB", (800, 600))   # JPEG decodes at reduced size
    im = im.convert("RGB"); im.thumbnail((256, 256))
    out = io.BytesIO(); im.save(out, "JPEG", quality=80); return len(out.getvalue())

if __name__ == "__main__":
    data = make_jpeg()
    print(f"source: 4000x3000 JPEG, {len(data)/1e6:.1f} MB")
    t = time.perf_counter(); [thumb(data) for _ in range(40)]
    one = (time.perf_counter() - t) / 40
    print(f"1 process : {one*1000:6.1f} ms per image")
    with ProcessPoolExecutor(12) as ex:
        list(ex.map(thumb, [data] * 12))
        t = time.perf_counter(); list(ex.map(thumb, [data] * 480, chunksize=8))
        par = (time.perf_counter() - t) / 480
    print(f"12 procs  : {par*1000:6.1f} ms per image wall-clock  ({one/par:.1f}x faster)")
    with ThreadPoolExecutor(12) as ex:
        t = time.perf_counter(); list(ex.map(thumb, [data] * 480))
        thr = (time.perf_counter() - t) / 480
    print(f"12 threads: {thr*1000:6.1f} ms per image wall-clock  ({one/thr:.1f}x faster)  <- Pillow releases the GIL")
    per_day = 1_000_000
    print(f"1M/day = {per_day/86400:.1f} images/s on average; peak 10x = {per_day/86400*10:.0f}/s;"
          f" one core handles {1/one:.0f}/s")

Make the invisible visible: Run it.

output · Python 3.12runs offline
source: 4000x3000 JPEG, 7.4 MB
1 process :   66.1 ms per image
12 procs  :    9.5 ms per image wall-clock  (6.9x faster)
12 threads:   10.9 ms per image wall-clock  (6.1x faster)  <- Pillow releases the GIL
1M/day = 11.6 images/s on average; peak 10x = 116/s; one core handles 15/s
# measured on the course machine (12 cores); your numbers will differ

What you see: One process: 66 ms per image. Twelve processes: 9.5 ms wall-clock, 6.9x faster. Twelve threads: 10.9 ms, 6.1x faster. Threads also scale here because Pillow releases the GIL during decoding, resizing and encoding. Not every library does, so I measure both.

pipelineruns offline
# illustrative
upload -> queue(key) -> [worker x 16 procs] -> object store
                |  ack after upload      |  key = hash/size.jpg  (idempotent)
                +-- 3 failures -> dead-letter queue -> alert
queue depth > N for 5 min  ->  add a machine

Why: The biggest win was draft: letting the decoder skip detail the thumbnail never needs. Cheaper per-image work beats more cores.

Land it I compute the load from the daily volume, measure the per-image cost, size machines with headroom for a 10x peak, and build an idempotent queue-driven worker pool, while checking whether the library releases the GIL before choosing processes or threads.

Likely follow-ups
"Processes or threads for this?"

Measurements decide, and here both scale. Pillow decodes and resizes in C and releases the GIL while it does, so threads in one process run in parallel on separate cores.

Threads share one copy of the code and the libraries, which saves memory. Processes cost more memory, since each carries its own interpreter, but they isolate failures: a corrupt file that crashes the C decoder takes down one worker, not the whole pool.

The memory arithmetic matters. A decoded 12-megapixel image is about 36 MB (12 million pixels x 3 bytes). Sixteen workers decoding at the same time hold roughly 16 x 36 = 576 MB of pixels, plus interpreter overhead per process. That fits a normal 16-core machine easily, so memory is not the deciding factor here.

I would pick one process per core for isolation and a clean restart policy (replace a worker after, say, 1,000 images to cap slow leaks). I would choose threads only if a profile showed memory or start-up cost mattering.

"How do you avoid shipping 7 MB through pickling?"

Because the arithmetic is bad. If the parent reads a 7 MB image and sends it to a worker through a pool, the bytes are copied three times: pickled in the parent, pushed through the pipe, and unpickled in the child. The thumbnail takes the same road back.

cost of shipping bytes at peakruns offline
7 MB x 3 copies x 116 images/s = 2,436 MB/s through one parent process
object key as the message      = a few dozen bytes x 116/s, nothing

All of that traffic passes through one parent process, which becomes the bottleneck long before the 16 cores are busy. It also means the parent holds image bytes in memory just to forward them.

So the message is an object key, and each worker downloads the image itself, in parallel, straight from storage. The same rule holds for any pool: send small descriptions of work, not the data, and let the worker fetch it (Q95).

"Would you use something other than Pillow?"

Possibly, and I would say so with a test attached. pyvips (a wrapper around libvips) streams the image in small pieces instead of decoding the whole thing, so it often uses less memory and can be faster on large images. A small Go or Rust service is another option if image work becomes the main job of the team.

But the speed I measured, about 66 ms per 4000x3000 JPEG, already comes from using Pillow well: JPEG draft mode asks the decoder to produce a half, quarter or eighth size image directly, skipping most of the work. Switching library is rarely the first win.

My test would be: take 1,000 real production images, run both libraries, and compare time per image, peak memory, and visual quality of the output. Formats matter too (PNG, WebP, HEIC), so the sample must contain the mix we really receive.

Because the worker only needs "key in, thumbnails out", the library can be swapped later without touching the queue or the storage layout.

"How do you know the system is healthy?"

I watch five signals, and the first one matters most.

  1. Age of the oldest message: this tells users how late their thumbnails are. A growing age means workers are behind.
  2. Images per second out: compare with the average of 11.6 per second and the peak target of 116.
  3. Failure rate and dead-letter count: a spike usually means a bad deploy or a new image format.
  4. p99 processing time: a rising tail points to huge images or a slow storage read.

I alert on queue age staying above its limit for five minutes, not on raw queue length, because a long queue that drains fast is harmless. With two machines handling about 200 images per second, a backlog of 1,000 images clears in about 1,000 / (200 - 11.6) = 5 seconds, so a brief spike is fine. A queue age that keeps rising means capacity is short, and that is when autoscaling should add machines.

Drill · Performance

Senior answers start with measurement, then data structures and algorithms, and only then native code or parallelism. Quote numbers you have measured, not slogans.

Q104. "How do you find where the time goes? timeit, cProfile, py-spy and Tachyon (3.15)."

Reveal answer

Strong answer First measure, do not guess. Different tools answer different questions.

timeit times a tiny piece of code many times: use it to compare two ways to write one expression. cProfile (with pstats) is a deterministic profiler: it records every function call, so it shows exact call counts, but it slows the program down and must be started with the program. A sampling profiler looks at the program's stack many times a second instead: low overhead, safe on a live service. py-spy is the best-known external sampler; Tachyon, new in 3.15 (python -m profiling.sampling), is the built-in one and can attach to a running process without a restart.

My workflow: sampling profile on the real workload to find the hot function, cProfile or line-level inspection to understand it, timeit to compare fixes, then re-measure the whole thing. For memory, tracemalloc.

I did not run py-spy here because it is not installed on this machine; I describe it from its documentation.

Picture it The same slow function seen by cProfile and by Tachyon.

The setup: slow_rules filters orders against a banned list, so every check scans the list.

profile_tools.py · Python 3.14runs offline
import cProfile, pstats, timeit, io

def slow_rules(orders, banned):
    return [o for o in orders if o not in banned]          # banned is a list

def parse(n):
    return [str(i) for i in range(n)]

def job():
    orders = parse(3000)
    banned = parse(3000)
    slow_rules(orders, banned)

print("timeit, 3 runs:", [round(t, 3) for t in timeit.repeat(job, number=1, repeat=3)])
pr = cProfile.Profile(); pr.enable(); job(); pr.disable()
out = io.StringIO()
pstats.Stats(pr, stream=out).strip_dirs().sort_stats("cumulative").print_stats(4)
print("\n".join(l for l in out.getvalue().splitlines() if l.strip()))

Make the invisible visible: Run it.

output · Python 3.14runs offline
timeit, 3 runs: [0.035, 0.035, 0.035]
         5 function calls in 0.037 seconds
   Ordered by: cumulative time
   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.037    0.037 profile_tools.py:9(job)
        1    0.036    0.036    0.036    0.036 profile_tools.py:3(slow_rules)
        2    0.001    0.000    0.001    0.000 profile_tools.py:6(parse)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

What you see: timeit said 0.035 s per run. cProfile shows nearly all of it (0.034 of 0.035 s) inside slow_rules itself, not in parse. That is the hot spot.

Make the invisible visible: Tachyon sampling a script for 3 seconds at 1,000 samples a second, no changes to the script.

python3.15 -m profiling.sampling run -r 1000 busy.py · Python 3.15.0rc1runs offline
Captured 3,048 samples in 3.05 seconds
Sample rate: 1,000.00 samples/sec
Error rate: 0.46
Profile Stats:
       nsamples   sample%   tottime (s)    cumul%   cumtime (s)  filename:lineno(function)
      3015/3015      99.4         3.015      99.4         3.015  busy.py:4(slow.<locals>.<genexpr>)
          11/11       0.4         0.011       0.4         0.011  busy.py:3(slow)
         4/3019       0.1         0.004      99.5         3.019  busy.py:4(slow)
         3/3033       0.1         0.003     100.0         3.033  busy.py:7(<module>)

What you see: 99.4 percent of samples were inside one generator expression in busy.py line 4: the list membership test. The other subcommands are attach (a running process), dump and replay.

Why: Both tools point at the same line, found without reading the code. Profile first, then change something.

Land it I measure first: a sampling profiler on the real workload to find the hot function, cProfile to explain it, timeit to compare fixes, and I re-measure after every change.

Likely follow-ups
"Why not just use cProfile everywhere?"

Because it pays a fee on every function call, and that fee distorts the picture. cProfile hooks the start and end of each call and records it. A program that spends its time in millions of tiny calls (a property getter, a small helper) is slowed a lot, and those tiny functions then look more expensive than they really are in the un-profiled run.

Two more limits. It must be started with the program, so it cannot be attached to a service that is already misbehaving. And it slows the process it measures, which is unwelcome in production.

I still use it for a narrower job: after a sampler has named the hot function, cProfile on a small reproduction tells me exactly what that function calls and how often.

"What does a sampling profiler miss?"

It misses exact call counts, and very short functions that never happen to be on the stack when a sample is taken. A function called a million times for a microsecond each might get few or no samples, even though the call count itself is a problem.

The percentages are still reliable for the question I care about. If a function is on the stack in 60 of 100 samples, the program spends about 60 percent of its time there. Statistics improve with more samples: thousands are solid, twenty are not.

Watch the error rate. Tachyon reported 0.46 in the run above; that counts samples it could not read, such as when it caught the process in the middle of a change. A low value is fine. A high one means the profile is partly blind, and I would lengthen the run before trusting it.

Many samplers also have separate CPU-time and wall-clock modes; check which one you are in, because they answer different questions.

"How do I profile a service already in production?"

The steps are the same on any version; only the command differs.

  1. Attach: on 3.15 run python -m profiling.sampling attach <pid>. On older versions use py-spy record --pid <pid> (or py-spy dump --pid <pid> for a single snapshot of every thread's stack).
  2. Sample a while: about a minute of real traffic. The service is not restarted and is barely slowed.
  3. Read the report: a table of hot functions or a flame graph, where wide bars are where the time goes.

The usual obstacle is permission. Attaching to another process needs ptrace rights, and on Linux the ptrace_scope setting or a container's default security profile often blocks it. In Kubernetes I add the SYS_PTRACE capability to a debug container, or run the profiler as the same user inside the pod.

I also profile one instance, not the whole fleet, so a mistake stays contained.

"How does the profile connect to asyncio code?"

A sampler answers "where is the CPU going?", and for asyncio that is only half of the story. Time spent running shows up clearly. If one coroutine does heavy parsing in the loop, it appears as a wide bar, and that is exactly the loop-blocking call from Q82.

Time spent waiting does not appear as CPU. A request that takes 800 ms because it awaits a slow database for 780 ms looks nearly empty in a CPU profile.

For waiting I use other tools. First, loop lag: schedule a task that sleeps 100 ms in a loop and logs how late it wakes up; a lag over a few tens of milliseconds means something is blocking. Second, asyncio's debug mode, which warns about callbacks slower than 0.1 seconds by default. Third, timing logs or tracing spans around each important await.

Together they separate "the CPU is busy" from "the code is waiting".

Q105 · Scenario. "An endpoint became 30 times slower as data grew; the cause was if x in some_list. Explain with Big-O and measurements."

Reveal answer

Strong answer x in some_list compares x with each element in turn until it finds a match, so it takes time proportional to the length: O(n). x in some_set computes a hash of x and jumps to the right bucket: O(1) on average.

A single check on a short list is harmless. The trap is a check inside a loop: checking m items against a list of n costs m x n, which is quadratic when both grow with the data. When data doubles, time quadruples. That is how an endpoint goes from fine to 30 times slower while nobody changed the code.

The fix is to build a set once, outside the loop: banned = set(banned_list). Building costs O(n) once; each check is then O(1). Sets need hashable items and lose order, so if I need both order and fast membership I keep a list and a set side by side.

Prove it with a measurement, not a theory, and rerun it after the fix.

Picture it List versus set membership at two sizes, then the endpoint-shaped loop.

The setup: Worst case for the list: the item sought is the last one. Then 5,000 lookups against a list or set of 1,000 and 20,000 items.

membership.py · Python 3.14runs offline
import timeit, random

for n in (1_000, 100_000):
    items = list(range(n)); as_set = set(items)
    probe = n - 1                                   # worst case for the list
    t_list = timeit.timeit(lambda: probe in items, number=200) / 200
    t_set = timeit.timeit(lambda: probe in as_set, number=200000) / 200000
    print(f"n={n:>7,}: list {t_list*1e6:9.2f} us   set {t_set*1e6:6.3f} us   ratio {t_list/t_set:9,.0f}x")

# the endpoint: 5,000 lookups against a growing list vs set
for n in (1_000, 20_000):
    items = list(range(n)); as_set = set(items)
    probes = [random.randrange(n * 2) for _ in range(5000)]
    a = timeit.timeit(lambda: [p in items for p in probes], number=1)
    b = timeit.timeit(lambda: [p in as_set for p in probes], number=1)
    print(f"endpoint, 5,000 checks, n={n:>6,}: list {a*1000:8.1f} ms   set {b*1000:6.2f} ms")

Make the invisible visible: Run it.

output · Python 3.14runs offline
n=  1,000: list      5.48 us   set  0.038 us   ratio       145x
n=100,000: list    537.83 us   set  0.038 us   ratio    14,223x
endpoint, 5,000 checks, n= 1,000: list     19.7 ms   set   0.17 ms
endpoint, 5,000 checks, n=20,000: list    385.2 ms   set   0.46 ms
# measured on the course machine; your numbers will differ

What you see: One check: list 5.3 microseconds at 1,000 items, 523 at 100,000 (100x more items, 100x more time: linear). The set stayed at 0.038 microseconds both times. The endpoint loop shows the compound effect: with 20 times more data the list version went from 20 ms to 389 ms (19x), while the set version went from 0.19 ms to 0.43 ms.

Slow: list membership

Scans the list for every order.

slow.pyruns offline
banned = load_banned()      # list
ok = [o for o in orders
      if o.id not in banned]

Fast: set membership

One hash lookup per order.

fast.pyruns offline
banned = set(load_banned())
ok = [o for o in orders
      if o.id not in banned]

The shift: Change the data structure, not the loop: one extra word turns O(n x m) into O(n + m).

Why: The growth is the story: linear cost per check times a number of checks that also grows. Big-O tells you the shape; the measurement tells you the size.

Land it I explain list membership as linear and set membership as constant on average, show the quadratic effect inside a loop with measured numbers, and fix it by building a set once.

Likely follow-ups
"Is a set always faster than a list?"

For membership tests, yes, once the collection has more than a handful of items. For very small ones, a list or tuple is fine. Comparing against five items takes microseconds, while a set pays for hashing the probe value and holds a larger table in memory.

The costs of a set are real. It uses more memory per item than a list, because its hash table keeps spare empty slots. Items must be hashable, so a list or dict cannot go in. Building one takes O(n) time, wasted if I look up only once or twice.

A set also loses order and cannot be indexed. If I only iterate, or need the first item or a position, a list is the right type.

My rule is about count and repeat: if I test membership many times against the same data, build a set once. If I test once, a plain scan is as cheap as building anything.

"What if the items are not hashable?"

Convert the item into something hashable that stands for it, and put those keys in the set. A list such as [3, 4] becomes the tuple (3, 4). A dict can become a tuple of its key or id fields. A group of items can become a frozenset, which is an immutable set that is hashable.

hashable stand-insruns offline
seen = {tuple(p) for p in points}        # points are [x, y] lists
if tuple(candidate) in seen: ...

keys = {order["id"] for order in orders}  # use the id, not the dict

A second route is to keep a sorted list and use bisect to find a position in O(log n). That works for anything that can be ordered, even if it cannot be hashed.

One warning: a class that defines __eq__ without __hash__ becomes unhashable (Q22). So the hash and the equality must be defined together, on fields that do not change while the object is in the set.

"How does dict lookup compare?"

It is the same speed. A dict is a hash table that stores a value next to each key, so key in d and d[key] are both O(1) on average. A set is built almost the same way, only without the values.

That is why a dict is the better tool when the loop does a lookup and then uses what it found. d.get(key) performs the membership check and returns the value in one hash lookup, instead of checking in and then fetching, which hashes twice.

The fast average depends on the table staying sparse; CPython resizes a dict when it is about two thirds full. The rare bad case is many keys sharing one hash (Q106).

A classic quadratic fix is to turn a list of records into a dict keyed by id once: by_id = {r.id: r for r in records}. Then every find the record with this id inside a loop becomes by_id[x], and the nested loop collapses to one pass.

"How do I spot this in code review?"

I look for a few shapes, and I ask what happens when the data grows ten times.

  1. Membership against a list inside a loop: if x in some_list in a for body or a comprehension.
  2. Per-item list operations: list.index, list.remove, list.insert(0, x) and list.pop(0) inside a loop. Each is O(n).
  3. Nested loops over two collections: matching orders to customers by comparing every pair.
  4. Repeated linear work: count(), sum() or len(list(...)) recomputed on every pass.

The arithmetic makes the comment concrete. Checking 1,000 items against a list of 100,000 is up to 1,000 x 100,000 = 100 million comparisons. With a set it is 1,000 hash lookups. When the data grows ten times, the first becomes 100 times worse.

In a review I suggest the fix and ask for a measurement (Q104) on realistic sizes, since a 20-item list is not worth the comment.

Q106. "Which time complexities of list, dict, set and deque must a senior know by heart?"

Reveal answer

Strong answer The table below is the one to carry in your head. "Average" means typical cases; hash tables can degrade to O(n) with pathological collisions, but Python's hashing makes that rare in practice.

Time complexity of common operations (n = size).
Operationlistdict / setdeque
append at endO(1) amortisedadd / set: O(1) avgO(1)
pop from endO(1)pop: O(1)O(1)
insert or pop at frontO(n)n/aO(1)
index by positionO(1)n/aO(n) in the middle
lookup by key / inO(n)O(1) avgO(n)
delete by value or keyO(n)O(1) avgO(n)
iterateO(n)O(n)O(n)
sortO(n log n)n/an/a

The two rows that cause real incidents are in on a list (Q105) and removing from the front of a list. A list is an array of pointers, so removing the first item shifts every other item one place. That is why a queue built on list.pop(0) gets slower as it grows, and why collections.deque exists.

Also remember list + list and slicing copy (O(n)), str += str in a loop (Q107), and that dict preserves insertion order since 3.7.

Picture it Draining 100,000 items from the front of a list and of a deque, and a few single operations.

complexity.py · Python 3.14runs offline
import timeit
from collections import deque

n = 100_000
lst = list(range(n)); dq = deque(range(n))
def pop_front_list():
    l = list(range(n)); 
    while l: l.pop(0)
def pop_front_deque():
    d = deque(range(n))
    while d: d.popleft()
print(f"drain {n:,} from the front: list.pop(0) {timeit.timeit(pop_front_list, number=1):.3f} s,"
      f" deque.popleft {timeit.timeit(pop_front_deque, number=1):.4f} s")
print(f"insert at front of 100k list : {timeit.timeit(lambda: lst.insert(0, 1), number=2000)/2000*1e6:.1f} us")
print(f"append to 100k list          : {timeit.timeit(lambda: lst.append(1), number=200000)/200000*1e6:.3f} us")
print(f"lst[50_000] index            : {timeit.timeit(lambda: lst[50000], number=200000)/200000*1e6:.3f} us")
print(f"dq[50_000] index (middle)    : {timeit.timeit(lambda: dq[50000], number=2000)/2000*1e6:.3f} us")

Make the invisible visible: Run it.

output · Python 3.14runs offline
drain 100,000 from the front: list.pop(0) 0.628 s, deque.popleft 0.0051 s
insert at front of 100k list : 19.5 us
append to 100k list          : 0.039 us
lst[50_000] index            : 0.031 us
dq[50_000] index (middle)    : 1.486 us
# measured on the course machine; your numbers will differ

What you see: Draining from the front: 0.627 s for the list, 0.005 s for the deque, 125 times faster. Inserting at the front of a 100,000-item list cost 19.5 microseconds while appending cost 0.037. Indexing the middle of a list took 0.026 microseconds but 1.5 microseconds on a deque: you pay for the fast ends.

list as a queue

pop(0) shifts every element.

list.pyruns offline
q = list(range(n))
while q:
    q.pop(0)       # O(n) each

deque as a queue

popleft is constant time.

deque.pyruns offline
q = deque(range(n))
while q:
    q.popleft()    # O(1) each

The shift: Choose the container whose cheap end matches how you use it.

Why: A list is a contiguous array: fast at the end and by position, slow at the front. A deque is a chain of blocks: fast at both ends, slow in the middle.

Land it I know that list is fast at the end and by index, dict and set are constant-time for lookup, and deque is constant-time at both ends, and I reach for deque instead of list.pop(0) and for a set instead of in-on-a-list.

Likely follow-ups
"What does "amortised O(1)" mean for append?"

It means that most appends are cheap, and the rare expensive one is paid for by the cheap ones around it. A list keeps spare room at the end. An append into spare room just writes one pointer.

When the room runs out, Python allocates a larger block, copies every pointer across, and frees the old one. That single append is O(n). But the new block is made bigger by a proportion, not by a fixed amount, so such copies become rarer as the list grows. Here is the real growth on Python 3.14.7, printing a line whenever the allocated size changed:

q106_append_growth.py outputruns offline
len  1 -> 88 bytes
len  5 -> 120 bytes
len  9 -> 184 bytes
len 17 -> 248 bytes
len 25 -> 312 bytes
len 33 -> 376 bytes

Over 40 appends there were only six resizes, and the gaps between them widen. Averaged, each append costs a constant. The trap: one append is not constant when latency matters (a request that triggers a resize of a huge list), so for tight latency I preallocate or use a deque.

"What about heapq and bisect?"

Both turn a plain list into a smarter structure without a new type. heapq treats a list as a binary heap: heappush and heappop are O(log n), and the smallest item is always at index 0. It suits priority queues, schedulers and "top k" jobs: heapq.nlargest(10, items) avoids sorting everything.

bisect does binary search in a list that is already sorted, in O(log n). bisect_left finds a position, and insort inserts at the right place.

The catch is that the insert is still O(n), because the items after the position must shift along. So insort in a loop over 100,000 items is quadratic. For a collection that must stay sorted and take many inserts, I use a third-party structure such as sortedcontainers.SortedList, or collect everything and sort once.

A heap is also not sorted. Only the smallest is guaranteed to be first. Iterating a heap list gives no useful order; to get items in order I pop them one by one.

"When is the dict worst case real?"

It is real when many keys share the same hash value, because then lookups turn into walks through a chain of colliding entries, and each step compares keys. A table of n colliding keys makes every insert O(n) and the whole build O(n squared).

Two ways it happens. The first is an attacker who crafts keys that collide, so a request with thousands of such keys freezes a server. Python defends against this for strings and bytes by seeding their hash randomly per process (hash randomisation, set with PYTHONHASHSEED).

The second is by accident: a class whose __hash__ returns a constant, or uses too few fields (Q22). Put 10,000 such objects in a set and the work is about 10,000 x 10,000 / 2 = 50 million comparisons instead of 10,000 lookups.

The habit that prevents it is to hash exactly the fields that define equality, and to be careful with user-controlled keys at the edge of a service. Cap how many keys a request may contain, as well.

"Is len() O(1)?"

Yes, for every built-in container: list, tuple, dict, set, deque, str, bytes. Each object stores its own size, and len() just reads that field. It does not count anything, so asking for the length in a loop condition is fine.

The trap is in other places. A generator has no len() at all, because it does not know how much it will produce until it runs. A custom class that defines __len__ by walking a structure makes every call O(n), and nothing warns the caller.

It has a second consequence. When you write if container:, Python asks for the truth value, and for classes without __bool__ it falls back to __len__. So a slow __len__ makes a plain if slow too. In my own classes I keep __len__ cheap by storing a counter, and if the count really is expensive I give it a method with a clear name (count()), so the cost is visible at the call site.

Q107. "Why is "".join(parts) preferred over += in a loop?"

Reveal answer

Strong answer Strings are immutable, so s += piece must in principle build a new string, copying everything built so far. Do that n times and the total copying is about n squared over two: O(n squared). "".join(parts) first adds up the lengths, allocates the result once, and copies each piece once: O(n).

In practice CPython has a shortcut. When the string being extended has only one reference, += can resize the memory in place, which makes simple loops fast. That shortcut is an implementation detail: it does not exist in every Python implementation, and it disappears the moment a second reference to the string exists.

So the honest answer is: in a simple loop on CPython the difference can be small, but join is never worse, it is never quadratic, and it does not depend on a hidden optimisation. I write join by habit and keep += for a few concatenations.

For building large text I also consider io.StringIO or writing straight to a file.

Picture it Measured, including the case where the shortcut is blocked.

The setup: Build a string of n pieces of 10 characters. First +=, then join, then += while a second reference to the string is kept in a list.

join_vs_concat.py · Python 3.14runs offline
import timeit

def concat(n):
    s = ""
    for i in range(n):
        s += "x" * 10
    return s

def concat_held(n):
    s = ""; keep = []
    for i in range(n):
        s += "x" * 10
        keep.append(s)             # a second reference blocks the in-place trick
    return s

def joined(n):
    return "".join("x" * 10 for _ in range(n))

for n in (10_000, 200_000):
    print(f"n={n:>7,}: += {timeit.timeit(lambda: concat(n), number=3)/3*1000:8.1f} ms"
          f"   join {timeit.timeit(lambda: joined(n), number=3)/3*1000:7.1f} ms")
n = 20_000

Make the invisible visible: Run it.

output · Python 3.14runs offline
n= 10,000: +=      0.4 ms   join     0.3 ms
n=200,000: +=      9.4 ms   join     6.2 ms
n= 20,000: += with a second reference   1579.3 ms
# measured on the course machine; your numbers will differ

What you see: In simple loops += was only a little slower than join (9.3 ms against 6.1 ms at 200,000 pieces): the in-place shortcut at work. With a second reference kept, only 20,000 pieces already took 1,537 ms: that is the quadratic cost, and here it dwarfs everything.

String +=

Fast only while one reference exists.

concat.pyruns offline
s = ""
for p in parts:
    s += p

join

Linear by construction.

join.pyruns offline
s = "".join(parts)

The shift: Collect pieces, combine once; do not depend on a hidden optimisation.

Why: The shortcut works only while Python can prove nobody else holds the string. Real code (a logging call, a list append, a closure) breaks that quietly, and the speed falls off a cliff.

Land it I use join because it is linear by construction, while += only looks fast on CPython when a hidden in-place optimisation applies, and it turns quadratic as soon as another reference exists.

Likely follow-ups
"What about f-strings in a loop?"

An f-string is fine. It builds one finished string from several parts in a single step: Python evaluates the pieces, computes the total size, and allocates once. f"{name}: {total}" is as good as join for a fixed set of parts.

The problem is not the formatting, it is the accumulating. Writing out += f"{row}," inside a loop still appends to an ever-growing string, so every iteration has the in-principle copying cost of +=. The f-string only builds the small piece; the append is the same append.

So the pattern I use is: format each item with an f-string (or str), put the pieces in a list, and join once at the end.

format each piece, join onceruns offline
pieces = [f"{r.id},{r.total}" for r in rows]
text = "\n".join(pieces)

If the output is huge, I skip even the list and write each line straight to a file or a StringIO.

"Does join work with non-strings?"

No. str.join demands that every item is already a str. An int or None in the sequence raises TypeError: sequence item 2: expected str instance, int found, naming the position of the offending item.

The fix is to convert as you go: ", ".join(str(x) for x in nums), or the shorter ", ".join(map(str, nums)).

A detail worth knowing: join needs to know the total length before it allocates, so internally it turns any iterator you give it into a list first. That means a list comprehension is usually a little faster than a generator expression inside join, and the generator saves no memory here. The "generators are lazy" advice does not apply to this call.

Also be careful with data that may be None. str(None) gives the text "None", which can quietly land in a file or a query. I filter or default those values first (str(x) if x is not None else "") so the output stays honest.

"What about bytes?"

Bytes work the same way, but the tools have different names. b"".join(chunks) is the equivalent of the string version and is linear. data += chunk on bytes builds a new object each time, so a loop that reads a socket and appends is quadratic. CPython's in-place shortcut for strings is not something to rely on here.

When I do not know the chunks in advance, I have two good options.

  1. bytearray: buf = bytearray() then buf.extend(chunk) (or +=), which is mutable and grows with the same spare-room trick as a list. Convert with bytes(buf) at the end.
  2. io.BytesIO: b.write(chunk), then b.getvalue(). It is also file-like, so library code that expects a file accepts it.

I choose bytearray for simple accumulation and BytesIO when something downstream needs a file object. A typical use is reading a download in 64 KB pieces: with bytes += a 100 MB body is copied thousands of times; with bytearray it is not.

"Where else does this "collect then combine" idea apply?"

It applies wherever each small operation has a fixed overhead that is larger than the work itself. Collect many items, then pay the overhead once.

Three examples I see often. In list code, append in a loop then one sort() beats inserting in sorted position each time. In database code, one statement per row means one network round trip per row. In file output, many tiny write calls cost more than a few buffered ones.

The database case is easy to work out. Assume a round trip takes 0.5 ms. One row per trip is 1,000,000 x 0.5 ms = 500 seconds of pure waiting. Batches of 1,000 rows mean 1,000 trips, so 1,000 x 0.5 ms = 0.5 seconds of waiting, plus the real insert work. (An assumption, not a measurement; the ratio of 1,000 holds.)

The trap is the opposite extreme: a batch so large that it holds memory or locks for too long. I pick a size from measurements.

Q108 · Scenario. "A plain loop over 10 million rows takes 40 seconds. What are your options, in order?"

Reveal answer

Strong answer I go from cheapest to most expensive, and I measure after each step.

  1. 1. Profile: check what the 40 seconds are really made of. Is it the loop body, a hidden O(n) lookup (Q105), disk or network, or conversion between types?
  2. 2. Fix the algorithm and data structures: a set instead of a list, one pass instead of three, precompute outside the loop. This often gives 10x to 1000x and costs almost nothing.
  3. 3. Use built-ins: sum, map, any, comprehensions and the standard library run their loop in C.
  4. 4. Vectorise: numpy or pandas, so the loop is done in compiled code on whole arrays.
  5. 5. Parallelise: split the rows into big chunks over processes (Q95).
  6. 6. Compile the hot loop: Cython, numba, or a Rust extension (Q109).

Parallelism comes late because it multiplies a slow solution by the number of cores. Vectorising often beats it on a single core.

Note on the numbers: my 10 million row loop took 0.65 s here, not 40 s, because the loop body is tiny. A 40-second loop has either a heavy body or an accidental O(n squared); step 1 finds out which.

Picture it The same computation at four levels, on 10 million numbers.

The setup: Sum of i * i % 7 for i up to 10 million: plain loop, generator with sum, numpy, and 8 processes.

slow_loop_options.py · Python 3.12 (venv)runs offline
import time, numpy as np
from concurrent.futures import ProcessPoolExecutor

N = 10_000_000

def loop():
    total = 0
    for i in range(N):
        total += i * i % 7
    return total

def comp():
    return sum(i * i % 7 for i in range(N))

def numpy_version():
    a = np.arange(N, dtype=np.int64)
    return int((a * a % 7).sum())

def chunk(rng):
    lo, hi = rng
    return sum(i * i % 7 for i in range(lo, hi))

Make the invisible visible: Run it.

output · Python 3.12runs offline
1. plain for loop                    0.67 s  result=19999999
2. generator + sum()                 0.66 s  result=19999999
3. numpy (vectorised)                0.17 s  result=19999999
4. 8 processes, plain Python         0.14 s  result=19999999
# measured on the course machine (12 cores); your numbers will differ

What you see: All four gave the same answer. The plain loop took 0.65 s. A generator inside sum was no faster (0.66 s): the loop body is still Python bytecode. numpy took 0.15 s (4.3x faster). Eight processes took 0.14 s (4.6x), using eight cores to get the same result as one core of numpy.

Why: Moving the loop into compiled code (numpy) gave nearly the speed-up of eight cores, with no pickling and no extra processes. Step 4 before step 5.

Land it I answer in order: profile, fix the algorithm, use built-ins, vectorise with numpy, parallelise in big chunks, and only then compile the hot loop, measuring each step.

Likely follow-ups
"When is numpy not an option?"

When the loop body depends on what happened in the previous step, or works on things that are not arrays of numbers. numpy shines when the same operation can be applied to every element at once, such as multiplying, summing or comparing columns.

Take a running balance with a cap: balance = min(balance + x, limit). Each step needs the result of the one before, so there is no way to hand the whole array to one numpy call. The same is true of parsing a text stream character by character, a state machine, or a recursive algorithm over a tree.

Work on Python objects is the other case: dicts, variable-length strings or objects with methods do not fit a numpy array. np.vectorize does not help; it is a Python loop in disguise.

For these, I reach for numba (@njit on a function of numbers and arrays), Cython, or a Rust extension (Q109), after steps 1 and 2 have confirmed the algorithm is right.

"Why was the generator version not faster?"

Because the generator changes how the loop is written, not how much work each item needs. A generator expression avoids building a list of 10 million items, which saves memory (Q55), but every element still runs through the interpreter: fetch a value, evaluate the body, resume the generator, yield.

The numbers on the page show where the time goes. A plain loop took 0.65 s for 10 million items, which is 65 nanoseconds per iteration. A job of 40 seconds over the same 10 million rows is 40 s / 10,000,000 = 4 microseconds per row, about 60 times more per row than that empty loop. So the loop itself is not the problem; what happens inside it is.

Speed comes from moving the per-item work out of the interpreter (a built-in like sum, a numpy call, compiled code) or from doing less work per item. A different spelling of the same Python loop rarely helps. I keep generators for memory, not for speed.

"Does Python 3.14 or the JIT change the order?"

It changes the constants, not the order. Python 3.11 added the specialising interpreter, which the release notes put at 10 to 60 percent faster than 3.10, about 25 percent on average. That is real, and it comes free by upgrading.

The JIT is smaller still. It arrived as an experimental, off-by-default option in 3.13, and 3.15 reports about 7 to 8 percent geometric-mean gain on one platform (reported by the project, not measured here). The free-threaded build helps threaded CPU work, but it does nothing for one thread and costs it about 23 percent single-thread overhead on my benchmark.

The arithmetic makes the point. If an upgrade gives 25 percent, a 40 second job becomes 32 seconds. The algorithm fix in step 2 can give 10x to 1000x, and numpy gave about 4x on this loop.

So I upgrade for the free gains, but I never plan a fix around "the next release will be faster". The order of options stays the same.

"How do I know I am done?"

When the measured time meets the requirement with a margin, and not before. "Faster" is not a goal. A target is: "the nightly job must finish inside its two-hour window, with the data doubling in a year."

That makes the stopping point calculable. If a 40 second job must run once a night, even 40 seconds is fine and I stop at step 0, which is to do nothing. If it must run per request in under 200 ms, then 40 seconds is nowhere near and I need the whole ladder. If the target is 10 seconds, step 2 (fix the algorithm) or step 3 (built-ins) may already reach it.

Each step on the ladder costs more to maintain than the one before. Rewriting a loop in Rust to save 8 seconds in a job nobody waits for is a bad trade.

I leave a growth margin, because data grows, and I record the final number with the data size it was measured at.

Q109. "When would you write a Rust extension (PyO3/maturin) rather than use Cython or numba?"

Reveal answer

Strong answer All of these move a hot loop out of the interpreter. The choice depends on the shape of the code and the team.

Native options for a hot Python loop.
OptionPick it whenCost or catch
numpy / pandasthe work is whole-array mathneeds array-shaped data; no help for branchy per-item logic
numbanumeric loops over arrays, quick win with @njitlimited Python subset, compile time on first call, awkward to deploy
Cythonspeeding up an existing Python codebase gradually, with C typesa new language dialect and a build step; memory safety is still your problem
Rust (PyO3 + maturin)a reusable, safe, fast library with real data structures, threads, no GIL during work; shipped to many usersneeds Rust skills and a toolchain; crossing the boundary costs, so keep calls coarse
C or C++ (pybind11, cffi)wrapping an existing native librarymanual memory safety; build complexity

I pick Rust when the code is a component that will live for years, handles untrusted input (parsers, serialisation), needs multi-threaded work, or must be shared as a wheel for several platforms. Memory safety and a good build tool (maturin) are the reasons. Well-known Python libraries (pydantic's core, ruff, polars) took this route.

I pick numba or Cython when I have one numeric kernel and want a quick win without a new language in the team. And I always try numpy first.

Picture it What a minimal Rust extension looks like, and the two commands that build and use it. I did not build this one for the page: it is shown as the shape of the work, not as measured output.

lib.rs (PyO3) and the workflowruns offline
# illustrative
use pyo3::prelude::*;

#[pyfunction]
fn weighted_total(prices: Vec<f64>, qtys: Vec<u32>) -> f64 {
    prices.iter().zip(qtys).map(|(p, q)| p * q as f64).sum()
}

#[pymodule]
fn pricer_native(m: &Bound<'_, PyModule>) -> PyResult<()> {
    m.add_function(wrap_pyfunction!(weighted_total, m)?)
}

# shell
#   maturin develop --release       # builds a wheel into the venv
#   python -c "import pricer_native; print(pricer_native.weighted_total([2.5], [4]))"

Why: The boundary is where the cost sits: converting a Python list into a Rust Vec copies it. Pass whole arrays or batches in one call, not one item per call, or the boundary eats the gain.

Land it I try numpy first, use numba or Cython for one numeric kernel, and choose Rust with PyO3 when the component is long-lived, safety-critical or multi-threaded, and always with coarse-grained calls across the boundary.

Likely follow-ups
"Why does the Python-Rust boundary cost anything?"

Because the two worlds store data differently, so every call has to translate. A Python list of floats is an array of pointers to separate float objects. Rust wants a contiguous block of 64-bit numbers. Passing the list means walking it, reading each object and copying the values into a Rust Vec. Results are converted back the same way, creating new Python objects.

Each call also has fixed costs: argument checking, interpreter lock state and building the return value.

This sets the design rule: make few, large calls. If one call processes a million items, the conversion is a small part of the total. If I call a Rust function a million times with one item each, the overhead can be larger than the work, and the code becomes slower than pure Python.

To avoid copies, I pass data that both sides can share without conversion, such as numpy arrays or bytes and buffer-protocol objects, which Rust can read in place.

"Does native code get around the GIL?"

It can, if the extension releases the GIL while it works. Extension code is not subject to the GIL while it is not touching Python objects. In PyO3 you do this with Python::allow_threads (renamed detach in recent PyO3 releases; check the docs for the version you use). Inside that closure the Rust code cannot touch Python objects, so I first copy what I need into Rust data.

The effect is real parallelism from ordinary threads: several Python threads call the same extension function, and each runs on its own core. This is the same reason Pillow scaled with threads in Q103, and why numpy, hashlib and zlib release the GIL on large inputs.

Two other routes work the same way. Numba has @njit(nogil=True), and Cython has with nogil: blocks.

One new point for free-threaded Python: extension modules must declare that they are safe without the GIL, or the interpreter may turn the GIL back on when it imports them. I check this before relying on 3.14t.

"How do users install it?"

They install a wheel: a prebuilt file that contains the compiled library. Building from source needs a Rust compiler on every user's machine, which is rarely acceptable.

  1. Build wheels per platform: a separate wheel for each operating system and CPU type (Linux x86-64 and ARM, macOS, Windows). Each wheel has tags in its filename, such as cp312-manylinux_x86_64, and pip picks the matching one.
  2. Per Python version, or abi3: by default one wheel per Python minor version. With PyO3's abi3 option, one wheel can serve all versions from a chosen minimum, at some cost in speed and features.
  3. Automate it: maturin builds the wheel, and CI tools like cibuildwheel run it across the platform matrix and publish to the package index (Q130).

I also publish a source distribution as a fallback, but I expect most users never need it. Without the wheel pipeline, a Rust extension becomes a burden for everyone who installs it.

"How would I justify the choice to a manager?"

With a short, numeric case that someone can check. A manager does not need Rust explained. They need cost against benefit.

First, evidence of where the time goes: a profile showing the function takes X percent of runtime. That sets the ceiling. By Amdahl's law, if the function is 70 percent of a 40 second job and I make it 20 times faster, the job takes 0.3 x 40 + 0.7 x 40 / 20 = 13.4 seconds, so about 3x overall, not 20x.

Second, a prototype on real data that shows the actual speed-up, since estimates are often wrong in both directions.

Third, the cost: weeks of work, a toolchain in CI, a wheel pipeline, and a team member who can maintain Rust when the author leaves.

Fourth, the cheaper alternative. If a numpy rewrite gets 80 percent of the gain in a day, I recommend that and say so. I propose Rust only when the cheaper options have been tried or ruled out.

Q110. "Do __slots__ make attribute access faster, or only smaller? Measure it."

Reveal answer

Strong answer Mainly smaller. A normal instance keeps its attributes in a per-object dictionary. A class with __slots__ stores them in fixed positions in the object, with no per-instance dict. That saves a lot of memory when you have many objects.

Access speed improves only slightly. Since 3.11 the specialising interpreter caches attribute lookups so well that normal instances are already fast, and the gap between a dict-backed and a slot-backed read is a few percent.

The costs of slots: you cannot add attributes that are not listed, there is no __dict__, weak references need __weakref__ in the slots, and multiple inheritance with several slotted bases is awkward. So use slots when you create millions of small objects, not as a general speed trick.

The measurement below uses 200,000 objects with two fields each.

Picture it Speed and memory of the same class with and without slots.

slots_speed.py · Python 3.14runs offline
import timeit

class Plain:
    def __init__(self): self.x = 1; self.y = 2
class Slotted:
    __slots__ = ("x", "y")
    def __init__(self): self.x = 1; self.y = 2

p, s = Plain(), Slotted()
for label, o in (("plain  ", p), ("slotted", s)):
    r = min(timeit.repeat("o.x; o.y", globals={"o": o}, number=2_000_000, repeat=5))
    w = min(timeit.repeat("o.x = 3", globals={"o": o}, number=2_000_000, repeat=5))
    print(f"{label}: read 2 attrs {r/2_000_000*1e9:5.1f} ns   write {w/2_000_000*1e9:5.1f} ns")
import tracemalloc
for cls in (Plain, Slotted):
    tracemalloc.start(); objs = [cls() for _ in range(200_000)]
    cur, _ = tracemalloc.get_traced_memory(); tracemalloc.stop()
    print(f"{cls.__name__:8} 200,000 objects: {cur/1e6:6.1f} MB")

Make the invisible visible: Run it.

output · Python 3.14runs offline
plain  : read 2 attrs  18.3 ns   write  12.5 ns
slotted: read 2 attrs  17.1 ns   write  11.2 ns
Plain    200,000 objects:   19.2 MB
Slotted  200,000 objects:   11.2 MB
# measured on the course machine; your numbers will differ

What you see: Reading two attributes took 18.3 ns on the plain class and 17.0 ns on the slotted one (about 7 percent). Writing: 12.4 ns against 11.2 ns. Memory for 200,000 objects: 19.2 MB against 11.2 MB, a saving of about 42 percent.

Plain class

Each instance owns a dict for its attributes.

plain.pyruns offline
class Plain:
    def __init__(self):
        self.x = 1
        self.y = 2
# can add self.z later

Slotted class

Fixed layout, no dict.

slotted.pyruns offline
class Slotted:
    __slots__ = ("x", "y")
    def __init__(self):
        self.x = 1
        self.y = 2
# self.z -> AttributeError

The shift: Slots trade flexibility for memory, and speed is a side effect of a few percent, not the reason.

Why: The win is memory and allocation, which matters at a million objects. At a thousand objects, the saving is kilobytes and not worth the restrictions.

Land it I say slots are mainly a memory optimisation, with only a few percent faster access, and I use them for millions of small objects, accepting no dynamic attributes.

Likely follow-ups
"What does @dataclass(slots=True) give?"

It generates the slots for you, and gives the memory saving with the dataclass conveniences (__init__, __repr__, __eq__). It needs 3.10 or later.

slotted dataclassruns offline
@dataclass(slots=True, frozen=True)
class Point:
    x: float
    y: float

There is a catch in how it works. A class's __slots__ must be set when the class is created, so the decorator builds a new class and returns it instead of changing the original. Anything holding a reference to the old class keeps the old one. That is the reason zero-argument super() in methods once failed in such classes; this has been fixed in recent versions, so check the notes for yours.

Two more details. Slotted instances have no __weakref__ unless you pass weakref_slot=True (3.11+). And default values work, but the slots are filled in __init__, not as class attributes.

I use it for value objects created in the millions, and plain dataclasses elsewhere.

"Do slots help with pickling or inheritance?"

Pickling works without extra code with the modern protocols (2 and above). The default pickle support copes with slots, so slotted objects can go through multiprocessing queues and caches. Very old protocols 0 and 1 are the exception.

Inheritance is where the saving gets lost. If a subclass does not define its own __slots__, Python gives it a __dict__ again, and every instance pays for the dictionary. So every class in the chain has to declare slots, and a base class with no slots (such as a plain object subclass that you forgot) undoes it silently.

Multiple inheritance has a second limit. Two parent classes that both add non-empty slots cannot be combined; Python raises TypeError: multiple bases have instance lay-out conflict. A mixin should therefore declare __slots__ = () so it adds nothing.

My check is simple: look at hasattr(obj, "__dict__") in a test for the classes I care about. If it is true, the slots are not doing their job.

"What is a better first step for memory?"

Measuring first, then picking the cheapest change. Slots are one tool among several, and not always the best.

  1. Measure: use tracemalloc (Q12) to see which line allocates the memory. On Python 3.14, one million small instances took 104.5 MB without slots and 64.4 MB with slots, a saving of 40 MB or about 38 percent. A measurement, not a guess.
  2. Change the shape of the data: a tuple or NamedTuple for a row, array.array or numpy for columns of numbers, interned strings for repeated text (Q20).
  3. Add slots: only when a million objects of one class really are needed.

The biggest saving is usually step 2. A numpy array of a million floats takes 8 MB, while a list of a million Python floats takes about 32 MB for the objects and pointers together. The representation matters more than the object overhead.

"Why was the speed gain so small?"

Because the normal case was already fast and has become faster in recent versions. Two things changed since 3.11.

First, the interpreter specialises the bytecode that reads an attribute after the code has run a few times. For a normal instance, it learns where the value sits and skips the generic lookup. For a slot, it learns the fixed offset. Both end up as a type check and one load at a known place, so the difference is small.

Second, normal instances no longer pay for a dictionary on every attribute read. Recent versions store the values inline in the object and build the real __dict__ only when something asks for it. That is also why the memory gap is narrower than it was: the dictionary is no longer built for every instance.

So slots are no longer a speed trick. They give a memory saving (104.5 to 64.4 MB on a million objects) and protection against typos like obj.nmae = 1, which raises AttributeError.

Q111 · Scenario. "A JSON API spends 60% of its time serialising responses. What are your options?"

Reveal answer

Strong answer First confirm the 60 percent with a profile, and see what is serialised: a large object graph, many small calls, or the same data again and again.

Options, cheapest first. Send less: only the fields the client needs, pagination, no nested objects the client ignores. Serialise once: avoid converting a model to a dict and then dict to JSON (two passes). Cache the serialised bytes of data that changes rarely. Use a faster encoder: orjson or msgspec are written in Rust or C. Let the model serialise itself: Pydantic v2's model_dump_json runs in its Rust core. Finally, compress large responses, which saves bandwidth but costs CPU.

A faster encoder is often a one-line change; sending less is the biggest win but needs a conversation about the API.

Beware of changing output: orjson returns bytes, not str, and handles datetimes and dataclasses differently from the standard library.

Picture it One order with 50 items, serialised four ways.

The setup: A Pydantic model Order with 50 items. We time each approach 5,000 times.

json_speed.py · Python 3.12 (venv)runs offline
import json, timeit
from pydantic import BaseModel
import orjson

class Item(BaseModel):
    sku: str; qty: int; price: float
class Order(BaseModel):
    id: int; items: list[Item]; note: str

order = Order(id=1, items=[Item(sku=f"S{i}", qty=i, price=i * 1.5) for i in range(50)], note="no onions")
d = order.model_dump()
N = 5000
def t(label, f): print(f"{label:34} {timeit.timeit(f, number=N)/N*1e6:7.1f} us per order")
t("order.model_dump() then json.dumps", lambda: json.dumps(order.model_dump()))
t("json.dumps(dict)", lambda: json.dumps(d))
t("order.model_dump_json()", order.model_dump_json)
t("orjson.dumps(dict)", lambda: orjson.dumps(d))
print("same bytes length:", len(json.dumps(d, separators=(",", ":"))), len(orjson.dumps(d)))

Make the invisible visible: Run it.

output · Python 3.12runs offline
order.model_dump() then json.dumps    51.6 us per order
json.dumps(dict)                      30.0 us per order
order.model_dump_json()               19.3 us per order
orjson.dumps(dict)                     3.5 us per order
same bytes length: 1810 1810
# measured on the course machine; your numbers will differ

What you see: Model to dict to JSON: 48.7 microseconds. Plain json.dumps of the dict: 30.1. Pydantic's own model_dump_json: 19.8. orjson: 3.8, about 8x faster than the standard library on identical content (both outputs are 1,810 bytes).

Stdlib: dict then dumps

Two passes, many temporary objects.

slow.pyruns offline
payload = order.model_dump()
body = json.dumps(payload)

One pass, native encoder

The model writes JSON in Rust.

fast.pyruns offline
body = order.model_dump_json()
# or: orjson.dumps(payload)

The shift: Convert once, and let compiled code do the bytes.

Why: The cheapest improvement was not clever: removing a double conversion saved 60 percent, and a faster library saved 90 percent.

Land it I confirm with a profile, then send less, serialise once, cache what is stable, and switch to a faster encoder such as orjson or the model's own JSON method, checking the output stays compatible.

Likely follow-ups
"Why is the standard library encoder slow?"

It has a C accelerator, but it is built for flexibility, and that has a price. It creates many small intermediate Python objects, checks for circular references by default, and calls back into Python through the default= hook for anything it does not know, such as a datetime.

A trap hides in the options. If you pass indent=2, the standard library switches to a slower pure-Python encoder. Pretty-printing every API response wastes speed on output no program needs.

orjson is written in Rust. It writes straight into one growing buffer and handles datetime, UUID and dataclasses natively. That is why it was about 8 times faster than the standard library on the payload measured on this page.

The price is compatibility: orjson.dumps returns bytes, not str, and its rules differ slightly (for example, non-string dict keys). I compare the output of old and new on real responses before switching.

"Does this matter if the database call takes 50 ms?"

Only if serialisation really takes 60 percent of the request, as the scenario says. Then the database call cannot be most of the time. If a typical endpoint spends its time in the database, I fix the query first and leave the encoder alone.

The numbers must agree with each other. Suppose the database call is 50 ms and is all of the remaining 40 percent. Then the request takes 50 / 0.4 = 125 ms and serialisation takes 75 ms. If a faster encoder makes serialisation 8 times faster, that part drops to about 9.4 ms, and the request takes 50 + 9.4 = 59.4 ms. That is 125 / 59.4 = 2.1 times faster overall, not 8 times.

So the order I follow is: confirm the 60 percent in a profile, then estimate the gain with the calculation above, then pick the option, and measure again.

"What if responses are huge lists?"

Stream them, and paginate. A response with a million items serialised at once needs the whole list in memory, then the whole JSON text in memory, and the client sees nothing until all of it is ready.

  1. Paginate: return 100 to 1,000 items per call with a cursor, so no client ever asks for everything.
  2. Stream: when a client really needs the whole set, send newline-delimited JSON (one object per line) from a generator, for example through a streaming response in FastAPI. Memory stays flat and the first bytes leave early.
  3. Know the limits: a streamed response sends the status code before the data, so an error half-way cannot change it. I send a final marker line or close the connection abnormally so the client can tell.

A reverse proxy that buffers the whole response again removes the benefit, so I check for that. A single huge JSON array cannot be parsed until it ends, which is why newline-delimited JSON is the better streaming format.

"How would I prove the win?"

I measure it at two levels, because a small test alone can mislead.

  1. The step itself: take a recorded real response (not a toy example) and time old against new encoder with timeit, many repeats. This proves the encoder is faster, but not that the endpoint is.
  2. The whole endpoint: run a load test before and after, on the same machine, with the same data and the same request mix, for several minutes. Compare throughput, p50 and p99. Run each version at least three times to see how much the numbers move by chance.
  3. The output: compare old and new responses byte for byte, or after parsing, for a few thousand real requests, so no field changed shape.

The micro-benchmark may show 8 times; the endpoint may show 1.5 times because it also waits for a database and does other work. I report the endpoint number, since that is what users feel, and say that the 8 times was only the encoder.

Q112. "What does lru_cache cost, and how do you choose maxsize?"

Reveal answer

Strong answer functools.lru_cache remembers results by arguments, so repeated calls skip the work. It has four costs.

Time per call: a hit still costs a dictionary lookup and bookkeeping, a bit more than calling a trivial function. Memory: it holds results and argument objects alive; with maxsize=None it never evicts, so memory grows with the number of distinct arguments. Correctness: it assumes the function is pure; cached data can be stale if the answer changes. Arguments must be hashable.

Choose maxsize from data, not by guessing: run the real workload, call cache_info(), and look at the hit rate and currsize. Pick the smallest size where the hit rate stops improving, and cap it so memory is bounded.

For methods, remember the cache holds self alive (Q50); for data that expires, I need a TTL cache instead.

Picture it The cost of a hit, and the memory of an unbounded cache.

lru_cost.py · Python 3.12 (venv)runs offline
import timeit, tracemalloc
from functools import lru_cache

def plain(n): return n * 2
cached = lru_cache(maxsize=1024)(plain)
for i in range(1024): cached(i)
print(f"plain call      {timeit.timeit(lambda: plain(5), number=1_000_000):.3f} s per 1M")
print(f"lru_cache hit   {timeit.timeit(lambda: cached(5), number=1_000_000):.3f} s per 1M")
print(cached.cache_info())

@lru_cache(maxsize=None)
def unbounded(key): return "x" * 100
tracemalloc.start()
for i in range(100_000): unbounded(f"user-{i}")
cur, _ = tracemalloc.get_traced_memory(); tracemalloc.stop()
print(f"maxsize=None after 100,000 distinct keys: {cur/1e6:.1f} MB held, {unbounded.cache_info().currsize:,} entries")

Make the invisible visible: Run it.

output · Python 3.12runs offline
plain call      0.048 s per 1M
lru_cache hit   0.077 s per 1M
CacheInfo(hits=1000000, misses=1024, maxsize=1024, currsize=1024)
maxsize=None after 100,000 distinct keys: 8.9 MB held, 100,000 entries
# measured on the course machine; your numbers will differ

What you see: A plain call of a trivial function cost 0.050 s per million; a cache hit cost 0.078 s. So the cache is only worthwhile when the real work costs more than about 30 nanoseconds extra. cache_info showed 1,000,000 hits and 1,024 misses. With maxsize=None and 100,000 distinct keys, 8.9 MB stayed in memory for that tiny function.

Why: A cache is a trade: memory and a small per-call cost for avoiding work. Both sides need a number.

Land it I treat lru_cache as a measured trade: it costs a lookup per call and memory per entry, so I cache only expensive pure functions, set a bounded maxsize from the observed hit rate, and watch cache_info.

Likely follow-ups
"How do I read cache_info()?"

Call cache_info() on the cached function. It returns hits, misses, maxsize and currsize. The hit rate is hits / (hits + misses). Here is a tiny run with maxsize=2 and six calls with arguments 1, 2, 1, 3, 1, 2:

q112_cache_info.py outputruns offline
CacheInfo(hits=2, misses=4, maxsize=2, currsize=2)

Two hits out of six calls is a 33 percent hit rate. The cache holds only two entries, so when 3 came in, the least recently used one (2) was evicted, and the next call for 2 missed again.

How I read it on a real workload: a full cache (currsize == maxsize) with a low hit rate means the set of values in active use is bigger than the cache, or the calls never repeat, so the cache only costs memory. A cache that never fills with a high hit rate is well sized. I raise maxsize in steps and stop when the hit rate stops improving.

"Is it thread-safe?"

The cache itself is safe to use from several threads. Its bookkeeping is protected, so the entries will not be corrupted.

But it does not make the function run only once per key. If two threads ask for the same missing value at the same moment, both see a miss, both run the function, and the second result overwrites the first. This is called a cache stampede, and it hurts when the function is expensive: ten threads asking for the same slow report each run it.

The result is the same either way for a pure function. The cost is duplicate work, and any side effect inside it happens more than once.

For expensive work I add a lock per key, so that the first caller computes while the others wait for the answer. A small dictionary of locks works, or a library with single-flight behaviour.

"What about staleness?"

lru_cache has no expiry. An entry stays until evicted by size, so changed data is served stale. For prices, permissions or feature flags, that can mean wrong answers for hours.

I have three ways to handle it, from simplest to most flexible.

  1. Clear on change: call func.cache_clear() when the underlying data is updated. Simple, but it drops every entry, not just the stale one.
  2. Time bucket in the arguments: add a value that changes every minute, so old entries are never hit again and age out by size.
    time bucketruns offline
    @lru_cache(maxsize=1024)
    def price(sku: str, minute: int): ...
    
    price(sku, int(time.time() // 60))
  3. A real TTL cache: cachetools.TTLCache expires each entry on its own timer.

I choose by how wrong the data may be: a minute of staleness is fine for a catalogue, and not fine for a stock balance.

"When is Redis better than lru_cache?"

Redis wins when the cache must be shared or must outlive the process. An in-process cache belongs to one worker. In a service with 8 worker processes, there are 8 separate caches. Each warms up on its own, so a key may be missed up to 8 times before every worker has it, and the same data takes 8 times the memory.

Redis fixes three things. All workers share one copy, so the hit rate is higher. Entries survive a restart, so there is no cold start. And entries can expire with a TTL or be cleared from outside.

The cost is a network hop, often around a millisecond inside one data centre, plus serialising the value. An in-process hit takes microseconds or less. So the in-process cache is better for small, hot, rarely changing data, and for cheap calls, where a Redis call would cost as much as the original work.

A common design uses both: a small lru_cache in front, then Redis, then the database.

Q113. ""Python is slow." How do you answer that in an interview, with numbers?"

Reveal answer

Strong answer I answer in three steps: agree, locate, quantify.

Agree where it is true: pure Python loops are slow. Here, a plain loop over 10 million numbers took 0.65 s, about 65 nanoseconds per iteration, against 0.15 s for numpy, 4x faster, and compiled code is faster still. Locate where time goes in real services: most are waiting on databases, networks and other services, which no language speeds up. A request that spends 50 ms in the database and 1 ms in Python gains nothing from a faster language. When CPU does dominate, the hot part is usually small and moves into numpy, a native library or Rust, which is how pydantic, polars and ruff are fast while being used from Python. Quantify the options: from my measurements, vectorising gave 4x, processes about 4x on four cores (0.82 s to 0.24 s), the free-threaded build 3.8x for threads on four cores, orjson 8x over the standard JSON, and a set instead of a list 14,000x on 100,000 items. And Python gets faster each release (3.11 reported 10 to 60 percent over 3.10, about 25 percent on average).

Then I say what I would do: profile first, fix the algorithm, then choose the cheapest lever.

Picture it The numbers I would quote, collected from this chapter's demos.

Measured on the course machine (12 cores). Your numbers will differ.
QuestionResult
10 million loop iterations, plain Python0.65 s (about 65 ns each)
same work with numpy0.15 s (4.3x faster)
4 CPU jobs: serial / 4 processes0.82 s / 0.24 s
membership in 100,000 items: list / set523 us / 0.038 us
JSON of one order: stdlib / orjson30.1 us / 3.8 us
40 async requests that wait: blocking / awaitingabout 1 s median / 51 ms

Make the invisible visible: Where the time goes in a typical request, as a rough picture to draw on a whiteboard.

one request, 60 ms total (typical shape)runs offline
# illustrative
database wait   |==========================================|  50 ms
network wait    |=====|                                       6 ms
python code     |==|                                          3 ms
serialisation   |=|                                           1 ms
-> a 10x faster language removes ~3 ms of 60. A better query removes 40.

Why: "Slow" has no meaning without "compared to what, doing what". Numbers turn a slogan into a decision.

Land it I agree that pure Python loops are slow, show where real services spend their time, and give measured levers: vectorising, processes, native libraries, better data structures and faster encoders, after profiling.

Likely follow-ups
"But Go or Rust would be faster, would they not?"

For CPU-bound code, yes, often by 10 to 100 times on tight loops. I do not argue with that. The question is whether my service is CPU-bound, and the profile answers it.

If the service waits on the database and other services, a faster language gains little. Take a request that spends 50 ms in the database and 1 ms in Python. Rewriting the Python part to be 10 times faster saves 0.9 ms: the request goes from 51 ms to 50.1 ms, which is a 1.8 percent improvement for a rewrite that costs months.

If the profile says CPU dominates, the better move is usually a surgical one. I rewrite the hot function or module (Q109), as pydantic, polars and ruff did, and keep the rest of the service in Python where changes are quick.

So the honest answer is: yes, they are faster at the loop; no, it does not usually decide whether my system is fast. I would say what the measured bottleneck is before I recommend a language.

"Is the GIL not a limitation?"

For CPU-bound Python threads on the regular build, yes, it is a real limit. The GIL lets only one thread run Python bytecode at a time, so four threads share one core's worth of work and add switching overhead. On this page four such threads ran at about 0.4 times the speed of the serial version.

It is not a limit for waiting. A thread blocked on a socket, a file or sleep releases the GIL, so hundreds of I/O-bound threads work fine.

When CPU work needs several cores, there are four ways around it.

  1. Processes: each has its own GIL, so work runs in parallel. Data moved between them is copied.
  2. Native code: numpy, Pillow and Rust extensions release the GIL while they work.
  3. Subinterpreters: each has its own GIL (3.14 has InterpreterPoolExecutor).
  4. Free-threaded build: the same threads ran 3.8 times faster (Q93), at a single-thread cost of about 23 percent on my benchmark.
"Is Python getting faster?"

Yes, steadily, in modest steps. 3.11 added the specialising interpreter (10 to 60 percent faster than 3.10, about 25 percent on average). 3.13 added an experimental JIT, off by default. 3.14 made the free-threaded build officially supported, though it is still a separate build. 3.15 reports further JIT gains of about 7 to 8 percent on one platform; I treat that as a reported figure.

Individual releases do not change the shape of a design, so I do not plan around them. A pure Python loop is still tens of times slower than compiled code.

But the gains compound and cost nothing. As an assumption, if each of three releases gave 10 percent, the product is 1.1 x 1.1 x 1.1 = 1.33, so a third more speed from upgrading alone.

The practical advice: keep the interpreter version current, since that is the cheapest speed-up there is, and test the new version on your own workload before you count on a number from release notes.

"When do you say "Python is the wrong tool"?"

The list is short, and each item has a reason.

Hard real-time work, where a deadline must never be missed. Python's garbage collector and reference counting can pause the program at unpredictable moments, and the interpreter gives no guarantees. Very small memory budgets, such as a microcontroller with kilobytes of RAM, where even a minimal interpreter is large.

A core engine where every microsecond counts, such as a matching engine, a codec or a packet processor, when the hot path cannot be isolated into a small native piece. And programs that must start in a few milliseconds and run once, where the interpreter's start-up time dominates.

For everything else the question is not language against language, it is whether the hot part can be isolated. If it can, I keep Python for the orchestration and put the hot piece in native code. If the hot part is the whole program, I choose another language, and I say that plainly in the interview rather than defend a tool I would not use.

Q114 · Scenario. "Memory spikes when the service reads a large CSV. Fix it."

Reveal answer

Strong answer The spike comes from loading the whole file into memory as Python objects. list(csv.DictReader(f)) makes one dictionary per row, each with its keys and string values, and Python objects are much bigger than the bytes on disk.

The fix is to stream: read one row at a time, process it, and let it be freed. for row in csv.DictReader(f): already does this, as long as you do not wrap it in list(). Keep only what you need: running totals, or batches of 1,000 rows written to the database.

If the work really needs the whole data set (sorting, grouping, joins), use a tool made for it: pandas with chunksize, polars (lazy scanning), DuckDB (queries the file directly), or load only the needed columns with compact types.

Also check the shape of the incoming data. Q19 and Q20 cover the representation: tuples, slots, numpy columns.

Picture it A 500,000-row CSV file read two ways, measured with tracemalloc.

The setup: load_all returns a list of dicts. stream computes the same total row by row.

csv_memory.py · Python 3.12 (venv)runs offline
import csv, tracemalloc, os, sys

path = "orders.csv"
if not os.path.exists(path):
    with open(path, "w", newline="") as f:
        w = csv.writer(f); w.writerow(["id", "sku", "qty", "price"])
        for i in range(500_000):
            w.writerow([i, f"SKU-{i % 900}", i % 5 + 1, f"{(i % 90) / 10 + 1:.2f}"])
print(f"file size: {os.path.getsize(path)/1e6:.1f} MB")

def load_all():
    with open(path, newline="") as f:
        return list(csv.DictReader(f))

def stream():
    total = 0.0
    with open(path, newline="") as f:
        for row in csv.DictReader(f):
            total += int(row["qty"]) * float(row["price"])
    return total

for fn in (load_all, stream):
    tracemalloc.start(); r = fn()
    cur, peak = tracemalloc.get_traced_memory(); tracemalloc.stop()
    print(f"{fn.__name__:9} peak {peak/1e6:7.1f} MB")
os.remove(path)

Make the invisible visible: Run it.

output · Python 3.12runs offline
file size: 11.3 MB
load_all  peak   166.0 MB
stream    peak     0.1 MB

What you see: An 11.3 MB file took a peak of 166 MB when loaded as dicts, about 15 times its size on disk. The streaming version peaked at 0.1 MB, regardless of file size.

Load everything

Memory grows with the file.

load.pyruns offline
with open(path, newline="") as f:
    rows = list(csv.DictReader(f))
total = sum(float(r["price"])
            for r in rows)

Stream

Memory stays flat.

stream.pyruns offline
total = 0.0
with open(path, newline="") as f:
    for row in csv.DictReader(f):
        total += float(row["price"])

The shift: Process rows as they arrive; never hold the whole file unless the algorithm demands it.

Why: Each dict carries its own hash table plus separate string objects for every value. The file's bytes are the small part.

Land it I stream the file row by row, keep only running state or small batches, and use pandas chunks, polars or DuckDB when the algorithm needs more than one pass.

Likely follow-ups
"Why is memory 15 times the file size?"

Because a Python object carries a lot of bookkeeping next to the data. A CSV row of 25 bytes becomes four separate string objects and a dictionary. Here is one real row, measured on Python 3.14.7:

q114_row_size.py outputruns offline
bytes in file : 25
4 str values  : 185
dict itself   : 184
total (keys shared) : 369

So 369 / 25 is about 15 times. The reasons: each str has a header of about 41 bytes (reference count, type, length, hash and flags) before the first character. The dict holds a table of hash, key and value slots. And a list of rows adds 8 bytes per row for the pointer.

The keys are shared between rows, so they cost nothing extra per row. The overhead is per small value, and a CSV is made of small values. A file of 1 GB can easily need 15 GB, which is why loading it into a list crashes the service.

"What if I must sort or group the whole file?"

Use a tool that does not need everything in Python objects, or that can spill to disk.

  1. DuckDB: SELECT customer, SUM(total) FROM 'orders.csv' GROUP BY customer reads the file directly, stores data in compact columns, and can spill to disk, so it handles files larger than RAM.
  2. Polars lazy mode: pl.scan_csv(...) builds a query plan and can run it in a streaming way, in chunks.
  3. SQLite or Postgres: load the rows in batches, add an index, and let the database sort and group on disk.
  4. Plain Python, external sort: sort chunks of, say, 100,000 rows in memory, write each to a temporary file, then combine them with heapq.merge, which reads one row per file at a time.

I use the database or DuckDB route for grouping and joins, because it is shorter and well tested. The external sort is worth writing by hand only when a dependency is not allowed.

"How do I insert rows into a database without a spike?"

Insert in batches, so memory holds one batch and the database sees fewer round trips. The loop collects a fixed number of rows, writes them, and lets them go.

batched insertruns offline
from itertools import batched   # 3.12+

with open(path, newline="") as f:
    for batch in batched(csv.reader(f), 1000):
        cur.executemany(
            "INSERT INTO orders VALUES (%s, %s, %s)", batch)
        conn.commit()

batched yields tuples of up to 1,000 rows, so memory stays at about one batch (roughly 1,000 x 369 bytes, about 0.4 MB, from the row measured above).

For very large loads, executemany is still one statement per row inside the driver in some libraries. PostgreSQL's COPY streams the rows in a single command and is much faster. I commit per batch, which keeps transactions short and lets a failed load resume from the last commit instead of starting over.

"What about uploads through a web endpoint?"

Do not read the request body into memory. A user can upload 2 GB, and a handful of such uploads at once will exhaust the service.

The safe pattern has four parts. First, set a maximum size, enforced as early as possible: at the reverse proxy (for example the nginx client_max_body_size setting) and again in the application, by counting bytes as they arrive rather than trusting the Content-Length header. Second, stream the body to a temporary file or straight to object storage in chunks, so memory holds one chunk at a time. Frameworks help here: Starlette's UploadFile keeps small uploads in memory and spools larger ones to disk.

Third, answer quickly with an id and process the file in a background job from storage, using the batched reading above. Fourth, validate the first rows and reject bad files early, so a wrong file fails in a second, not after an hour.

The aim is that memory use depends on the chunk size, not on what the user sends.

Q115 · Design. "Plan a ten-times throughput improvement for a Python service without rewriting it."

Reveal answer

Strong answer I treat it as an engineering project with a measurement at every step. Ten times rarely comes from one trick; it comes from removing the biggest bottleneck, then the next one.

  1. Baseline: build a repeatable load test, record throughput, p50 and p99, CPU, and memory. Without it nothing else counts.
  2. Profile under load: sampling profile and database slow-query log. Find where time goes.
  3. Remove waste: N+1 queries, missing indexes, repeated work, list-in-list lookups, double serialisation. Often 2x to 3x.
  4. Cache and batch: cache stable data, batch database and network calls, add connection pooling.
  5. Use the hardware: run one worker per core, async or threads for waiting, processes for CPU, native libraries for hot loops.
  6. Scale out: stateless instances behind a load balancer, once a single instance is efficient.

The arithmetic matters: Amdahl's law. If a part that takes 80 percent of the time becomes 10 times faster, the service gets only 3.57x faster; the remaining 20 percent now dominates. To reach 10x I have to work on several parts.

I also decide in advance what "done" means (target throughput at an agreed p99), and what I will not do, such as a rewrite, which would be the next phase if this fails.

Picture it How much each fix must give, worked out with the formula.

amdahl.py · Python 3.14runs offline
# if a fraction p of the time is sped up by s, the whole service speeds up by 1/((1-p)+p/s)
def total(p, s): return 1 / ((1 - p) + p / s)
for p in (0.5, 0.8, 0.9, 0.95):
    print(f"{p:.0%} of time made 10x faster -> whole service {total(p,10):4.2f}x;"
          f" made infinitely faster -> {total(p,1e12):5.2f}x")

Make the invisible visible: Run it.

output · Python 3.14runs offline
50% of time made 10x faster -> whole service 1.82x; made infinitely faster ->  2.00x
80% of time made 10x faster -> whole service 3.57x; made infinitely faster ->  5.00x
90% of time made 10x faster -> whole service 5.26x; made infinitely faster -> 10.00x
95% of time made 10x faster -> whole service 6.90x; made infinitely faster -> 20.00x

What you see: Making half of the time 10 times faster gives 1.82x. Making 90 percent of the time 10 times faster gives 5.26x, and even making it infinitely fast would give 10x at most. To reach 10x overall, the part that is not touched must be under 10 percent.

a plan that reaches 10x (example, to be confirmed by measurement)runs offline
# illustrative
step                         share of time   speed-up   running total
fix N+1 queries / add index        45 %         5x           1.5x
cache hot reference data           15 %         10x          2.2x
orjson + stream big responses      10 %         8x           2.6x
workers = cores, pool sizing       --           ~3x (cap)    ~7x
batch writes, drop double work     15 %         6x           ~10x

Why: Nobody gets 10x from the last step. The plan is a sequence of measured bites; each step changes where the next bottleneck is, so I re-profile after every one.

Land it I plan it as measure, profile, remove waste, cache and batch, use the hardware, then scale out, using Amdahl's law to show that several bottlenecks must fall, and re-profiling after each step.

Likely follow-ups
"What if the profile shows time spread evenly?"

Then there is no single hot spot, and the gains come from structure, not from tuning one function. I look at three things.

First, call counts. A flat profile is often a request that makes fifty small calls: fifty database queries of 4 ms each is 200 ms, spread so evenly that no single call looks bad. Batching them into two queries is the fix, the classic N+1 query problem. The profile shows the shape only if I group by what the code is doing, not by function.

Second, waiting. I check that the service is not waiting on the same slow dependency in many places, and whether wall time is far above CPU time. If so, the work is waiting, and concurrency or caching helps more than faster code.

Third, layers: serialising, validating, logging and middleware that each cost a little and add up. Removing a layer that does nothing is cheap.

If none of this helps, the remaining lever is running more instances.

"How do you avoid breaking things while optimising?"

By making each change small, reversible and compared with the old behaviour. A faster wrong answer is a regression.

  1. Characterise first: before touching anything, record real requests and responses for the endpoints I will change, and keep the test suite green at every step.
  2. One change at a time: if I make three changes and the numbers move, I cannot tell which helped or which broke things.
  3. Compare old and new: run both paths on the same inputs, either in a test or as a shadow call in production, and alert when answers differ.
  4. Ship carefully: put it behind a flag or on a canary taking 5 percent of traffic, watch errors and p99, and widen only when they are flat.

Caching changes need extra care, because a stale answer is a new kind of bug. I add the cache with a short expiry first and lengthen it only after watching for stale reads. Every step also has a rollback that takes minutes, not a redeploy of everything.

"When would you stop and rewrite?"

When the evidence says the cost is in Python code itself, and cheaper options are used up. Three checks, in order.

First, the profile shows CPU-bound Python in the core of the service after the algorithm and query fixes, and the slice is large. Second, a prototype of the native version, run on real data, shows a gain worth the cost. Third, the team can maintain it.

Amdahl's law gives the ceiling. Here is the arithmetic for a function that takes 80 percent of the time:

q115_amdahl.py outputruns offline
one part (80%) made 10x faster -> 3.57x overall
same part made infinitely faster -> 5.00x at most

So a rewrite of an 80 percent hot spot cannot give more than 5 times overall, however good the native code is. That is why I rewrite the hot module, not the service, and why a 10 times target needs the other bottlenecks removed as well.

"How do you report progress?"

With a table, one row per step, showing before and after on the same load test. The structure matters more than the numbers.

StepWhat I recordWhy it matters
BaselineThroughput, p50, p99, CPU, memoryEverything else is measured against it
Each changeSame metrics, same load test, before and afterShows which change earned its keep
Running totalOverall gain against the 10x targetShows the gap that remains
Next candidateThe next biggest cost from a fresh profilePrevents optimising the wrong thing

A weekly note with this table keeps the project honest. It also makes diminishing returns visible: if steps 1 and 2 gave 2x and 1.5x and step 3 gave 1.05x, I can tell the manager that the next 10 percent costs more than the first 200 percent, and let them decide whether to stop.

I report p99 next to throughput, because a service can double throughput by letting the slowest requests wait, and users would feel that.

11 · DrillDrill: Types, Packaging, Testing and Production Design — Q116–Q150

The last thirty-five questions move from the interpreter to the codebase around it: typing, packaging, testing, and the production scenarios and review comments that fill the final rounds. Design questions end the section; they ask you to plan, so answer with steps, numbers and what you would measure.

Drill · Typing

Expect to be asked what the checker cannot see: Any, casts, unvalidated input. Know Protocol, generics with the 3.12 syntax, ParamSpec and the 3.14 annotation change.

Q116. "Type hints are ignored at runtime — so why use them?"

Reveal answer

Strong answer Python itself does not check them: the interpreter stores annotations and moves on. The value comes from other tools that read them.

A static type checker (mypy, pyright, ty) reads the hints without running the program and reports mismatches, such as passing a str where a float is expected, or using a value that may be None. These are bugs found at review time instead of in production.

Editors use hints for autocomplete, jump-to-definition and safe renames. Runtime libraries read them too: Pydantic validates data from them, FastAPI builds request parsing and documentation from them, dataclasses create fields from them. And readers get documentation that cannot drift as easily as a comment.

The cost is writing and maintaining them, and a false sense of safety if the checker is not in CI or if Any creeps in (Q120).

Where a value crosses a boundary (JSON in, a database row), hints do not validate it. That is where Pydantic or explicit checks are needed (Q119).

Picture it The same function, run and checked.

hints_ignored.py · Python 3.12 (venv)runs offline
def total(price: float, qty: int) -> float:
    return price * qty

print(total("ab", 3))          # wrong type: Python does not check
print(total(2.5, 2))

Make the invisible visible: Run it, then check it with mypy.

python hints_ignored.pyruns offline
ababab
5.0
mypy hints_ignored.py · mypy 2.4.1runs offline
hints_ignored.py:4: error: Argument 1 to "total" has incompatible type "str"; expected "float"  [arg-type]

What you see: Python ran it: "ab" * 3 is a legal operation, so it printed ababab with no complaint. mypy rejected the call before running it: Argument 1 to "total" has incompatible type "str"; expected "float".

Make the invisible visible: The bug from the incident: a function that may return None.

find_rule.pyruns offline
from dataclasses import dataclass

@dataclass
class Rule:
    amount: int

RULES = {"FIRST50": Rule(50)}

def find_rule(code: str) -> Rule | None:
    return RULES.get(code)

def discount(code: str) -> int:
    return find_rule(code).amount      # ❌ None is possible
mypy find_rule.py · mypy 2.4.1runs offline
find_rule.py:13: error: Item "None" of "Rule | None" has no attribute "amount"  [union-attr]
Found 1 error in 1 file (checked 1 source file)

No hints: found at runtime

The crash happens in production.

untyped.pyruns offline
def find_rule(code):
    return RULES.get(code)
find_rule(c).amount   # may be None

Hints: found by the checker

The error is reported before the run.

typed.pyruns offline
def find_rule(code: str) -> Rule | None:
    return RULES.get(code)
find_rule(c).amount   # mypy: error

The shift: Types move a class of bugs from the pager to the pull request.

Why: The checker found AttributeError: 'NoneType' object has no attribute 'amount' before the first request did.

Land it I say hints are not enforced by Python but give a static checker, editors and libraries something to work with, so I run a checker in CI and validate untrusted data at the boundaries.

Likely follow-ups
"Do hints slow Python down?"

Almost not at all at call time. Hints do not run on each call, so a function with annotations is not slower to call than one without.

The cost is at definition. Before 3.14, Python evaluates annotations once when it runs a def or class statement and stores the results in __annotations__. In 3.14 evaluation is lazy: Python stores a small function that builds the annotations only when someone reads them (Q122). Either way it is paid once, at import.

That import-time work is small for one module but visible in a very large typed codebase. It is one reason lazy evaluation was added.

There is one trap: libraries that read the hints at runtime do pay. Pydantic, FastAPI and dataclasses inspect annotations when a class is created, building validators from them. That work also happens once per class, at import, not per request.

So I would never skip hints for speed.

"Is there a way to enforce them at runtime?"

Yes, with libraries that read the hints and check values when the code runs. Python itself does nothing.

runtime checking optionsruns offline
from pydantic import validate_call

@validate_call
def charge(amount: int, currency: str) -> str:
    return f"{amount} {currency}"

charge("12", "EUR")   # "12" is converted to 12; "abc" raises ValidationError

validate_call checks and converts the arguments. typeguard and beartype check that arguments and return values match the hints and raise if not, without conversion.

The cost is real: the check runs on every call, which adds overhead. In a hot loop that can multiply the time of a small function. So I use runtime checking at boundaries where data arrives from outside, and in the test suite, where I can switch a checker on for the whole run. Inside the core code, the static checker is enough.

"What does gradual typing mean?"

It means typing can be added bit by bit, and code without hints is not an error. The checker treats a missing hint as Any, which is compatible with everything in both directions.

That allows a safe path for existing code. I annotate one module, the checker verifies it, and unannotated code around it carries on. Calls from typed code into untyped code are accepted, but the result of an unannotated function is Any, so the checker stops following it.

There is a surprising detail: by default mypy does not even look inside the body of a function that has no annotations. A typo in an unannotated function passes silently. The option --check-untyped-defs turns on checking of those bodies without requiring hints.

The downside is that unchecked parts hide errors, and the hiding spreads (Q120). So gradual typing needs a plan: where the boundary is today, and a ratchet that moves it forward (Q125). Without that, "gradual" tends to become "never".

"Is it worth it for a small script?"

Less so, and I say it plainly. For a 50-line script that one person runs, I often skip them. The script can be read in a minute.

The value of hints grows with three things: the number of people, the age of the code and how often it changes. A function used by five other modules, written by a person who left, is where "does this return a list or a dict?" costs an hour. With hints and a checker in CI, that same question is answered by the editor, and a refactor that breaks callers is caught before merging.

A cheap middle path is to annotate only the public functions and the data models, since boundaries are where mismatches happen.

Even in a small script, hints on the function signatures help the editor complete names and warn about None. If the script grows into a service, I add the checker then.

Q117. "Protocol versus ABC — structural versus nominal typing."

Reveal answer

Strong answer Nominal typing asks: "did you declare that you are one of these?". An ABC (abstract base class) works that way: a class must inherit from it, and the checker (and isinstance) knows it only through that declaration. Java interfaces are nominal.

Structural typing asks: "do you have the methods I need?". A Protocol describes a shape: any class with a matching send(self, msg: str) -> None is accepted by the checker, with no inheritance. It is a checked form of duck typing.

Use a Protocol for what a function needs from its arguments, especially for third-party classes you cannot change and for test fakes. Use an ABC when you want shared implementation, a registered family of classes, a runtime isinstance check, or a hard guarantee that subclasses implement the abstract methods when instantiated.

A Protocol is checked only by the type checker, unless marked @runtime_checkable, and then isinstance only checks that the method names exist.

Picture it The same function accepting a class that never heard of our interface.

Java · interface (nominal)

The class must say implements Notifier.

Notifier.javaruns offline
interface Notifier {
  void send(String msg);
}
class SmsClient
    implements Notifier { ... }
// vendor class without it: no

Python · Protocol (structural)

Matching method signature is enough.

sink.pyruns offline
class Sink(Protocol):
    def send(self, msg: str) -> None: ...

class SmsClient:   # no inheritance
    def send(self, msg: str) -> None: ...

The shift: Java asks who you are declared to be; a Protocol asks what you can do.

protocol_vs_abc.py · checked by mypy 2.4.1runs offline
from abc import ABC, abstractmethod
from typing import Protocol

class Notifier(ABC):                    # nominal: must inherit
    @abstractmethod
    def send(self, msg: str) -> None: ...

class Sink(Protocol):                   # structural: shape is enough
    def send(self, msg: str) -> None: ...

class SmsClient:                        # third-party, knows nothing about us
    def send(self, msg: str) -> None:
        print("sms:", msg)

def alert_abc(n: Notifier) -> None: n.send("hi")
def alert_proto(n: Sink) -> None: n.send("hi")

alert_proto(SmsClient())                # fine
alert_abc(SmsClient())                  # error: not a subclass

Make the invisible visible: Run mypy.

mypy protocol_vs_abc.pyruns offline
protocol_vs_abc.py:19: error: Argument 1 to "alert_abc" has incompatible type "SmsClient"; expected "Notifier"  [arg-type]
Found 1 error in 1 file (checked 1 source file)

What you see: The Protocol function accepted SmsClient (no error on line 18) while the ABC function rejected it, because SmsClient does not inherit from Notifier.

Why: A vendor's class cannot be edited to inherit from your ABC, but it can satisfy your Protocol.

Land it I use a Protocol to describe what a function needs, so any matching class and any fake works without inheritance, and an ABC when I want shared code or runtime enforcement.

Likely follow-ups
"When is an ABC better?"

When the classes share real behaviour, when I need a hard guarantee, or when I need a reliable runtime check.

First, shared implementation. An ABC can hold concrete methods that call abstract ones (the template method pattern), and subclasses inherit them. A Protocol is only a description and holds no shared code that implementers receive unless they inherit from it explicitly.

Second, early failure. If a class forgets an abstract method, instantiating it raises TypeError at once, even without a type checker:

abstract method enforced at creationruns offline
class Sink(ABC):
    @abstractmethod
    def send(self, msg: str) -> None: ...

Third, isinstance(x, Sink) against an ABC is reliable, since it asks "did you declare yourself one?", and plugin systems can use register() to accept classes you cannot edit.

If none of those applies, I choose the Protocol, because it needs no inheritance and is lighter for callers.

"What does @runtime_checkable do?"

It lets isinstance and issubclass work with a Protocol. Without it, isinstance(x, Sink) raises TypeError. The check is weak, and this run shows how weak:

q117_runtime_checkable.py outputruns offline
True
False

The first line is for a class whose send takes three unrelated arguments, nothing like the Protocol's send(msg: str) -> None. It still passed, because isinstance only checks that an attribute named send exists. It does not look at the parameters, the types or the return value. The second line, an object with no send, correctly fails.

So the static checker is the real guarantee, and the runtime check is a quick sanity test. I use @runtime_checkable sparingly, for example at a plugin boundary to give a clear error early, and I never rely on it to prove that an object can be used safely.

"How do Protocols help testing?"

They make fakes trivial. A function that accepts a Sink Protocol can be tested with a few lines, with no mocking library and no inheritance:

a three-line fakeruns offline
class FakeSink:
    def __init__(self): self.sent = []
    def send(self, msg: str) -> None: self.sent.append(msg)

notify(FakeSink(), "hello")

The fake is a real, plain class. The test then asserts on fake.sent.

There is a real advantage over unittest.mock.Mock. A mock accepts any attribute and any call, so a typo like sink.sned(...) passes silently in the test and fails in production. The fake must match the Protocol, and the type checker verifies that, so changes to the interface break the fake at review time (Q137).

I still use mocks for checking calls to external systems, but for simple collaborators a Protocol with a small fake gives clearer tests.

"Can a Protocol have attributes and properties?"

Yes. A Protocol can declare data attributes and properties, and then any implementer must provide them with a compatible type.

protocol with attributesruns offline
class Named(Protocol):
    name: str                 # must be readable AND writable

class Labelled(Protocol):
    @property
    def label(self) -> str: ...   # readable is enough

The difference matters. A plain name: str means the attribute is mutable, so a frozen dataclass (read-only) is rejected, and so is a class that exposes it as a read-only property. The checker reports that as a mismatch in mutability.

A read-only @property in the Protocol accepts almost everything: a plain attribute, a property, a frozen dataclass field. So when a function only reads the value, I declare a property, which makes the Protocol much easier to satisfy.

The messages from mypy and pyright on this point are clear, and they name the member that does not match.

Q118. "Generics with the 3.12+ syntax: def first[T](xs: list[T]) -> T and type aliases."

Reveal answer

Strong answer A generic function or class works for many types while keeping the link between them: "if I give you a list of int, you give me back an int". T is a placeholder the checker fills in at each use.

Before 3.12 you had to create a module-level T = TypeVar("T") and use it in signatures, which was easy to get wrong. PEP 695 (3.12) puts the parameter in square brackets next to the name: def first[T](xs: list[T]) -> T and class Box[T]:. The scope of T is only that function or class, so there is no stray global.

The type statement defines an alias that is lazily evaluated: type Pair[T] = tuple[T, T]. Forward references work without quotes, and recursive aliases are possible.

Bounds and constraints use a colon: def biggest[T: (int, float)](a: T, b: T) -> T or [T: Comparable].

Picture it The three forms, checked by mypy.

generics.py · Python 3.14 syntax, checked by mypy 2.4.1runs offline
def first[T](xs: list[T]) -> T:
    return xs[0]

class Box[T]:
    def __init__(self, item: T) -> None:
        self.item = item

type Pair[T] = tuple[T, T]

reveal_type(first([1, 2]))
reveal_type(first(["a"]))
reveal_type(Box(2.5))
p: Pair[int] = (1, 2)
bad: Pair[int] = (1, "x")

Make the invisible visible: Run mypy.

mypy generics.pyruns offline
generics.py:10: note: Revealed type is "int"
generics.py:11: note: Revealed type is "str"
generics.py:12: note: Revealed type is "generics.Box[float]"
generics.py:14: error: Incompatible types in assignment (expression has type "tuple[int, str]", variable has type "tuple[int, int]")  [assignment]
Found 1 error in 1 file (checked 1 source file)

What you see: The checker inferred int for a list of ints, str for a list of strings, and Box[float] for Box(2.5). It rejected (1, "x") for Pair[int], since both members must be the same T.

Old style TypeVar

A module-level variable and an import.

old.pyruns offline
T = TypeVar("T")
def first(xs: list[T]) -> T:
    return xs[0]

3.12 bracket syntax

The parameter is scoped to the function.

new.pyruns offline
def first[T](xs: list[T]) -> T:
    return xs[0]

The shift: The new syntax puts the type parameter where it lives, with no global to misuse.

Why: The generic keeps the connection between input and output types; Any would lose it.

Land it I write generics with the 3.12 bracket syntax, where the type variable is scoped to the function or class, and use the type statement for aliases, using bounds when the function needs some capability.

Likely follow-ups
"What did the old TypeVar style look like?"

The old way needed a module-level variable and a separate step:

before and after 3.12runs offline
from typing import TypeVar, Generic
T = TypeVar("T")                      # old: name repeated, global

def first(xs: list[T]) -> T: ...
class Box(Generic[T]): ...

def first[T](xs: list[T]) -> T: ...   # 3.12+: scoped, no import
class Box[T]: ...

The old style still works and is required for code that must run on 3.11 or older. Its downsides are easy to see. The string "T" and the variable name must match by hand, the variable is a global that leaks into the module, and the same T can be reused by mistake in unrelated functions, which links them.

Variance (below) also had to be declared by hand with covariant=True. The new syntax infers it.

The typing_extensions package backports many typing features, but not the new syntax itself, since that is grammar. I use the new form in anything 3.12+ only.

"What are covariance and variance, briefly?"

It is about whether a container of a subtype can stand in for a container of the supertype. Take Cat as a subclass of Animal. Can a list[Cat] be used where list[Animal] is expected?

For a mutable list, no, and the reason is the write. If the function receives a list[Animal], it may do xs.append(Dog()). That would put a dog in a list that the caller believes holds only cats. So mutable containers are invariant: list[Cat] is not a list[Animal].

For read-only containers it is safe. A Sequence[Cat] can be used where Sequence[Animal] is expected, because the receiver can only read animals out. That is covariant. The opposite case is contravariant: a function that accepts any Animal can stand in for one that accepts Cat, which is why function parameter types are contravariant.

With the 3.12 syntax, the checker infers which one applies from how T is used in the class. With the old style, I write covariant=True myself.

"How does this relate to Java generics?"

The syntax looks alike, but the difference is that Python's generics are only for the checker. Java writes List<T> and Python writes list[T].

In Java, the compiler checks generics and then erases them. At runtime a List<String> and a List<Integer> are the same class, which is why you cannot write new T() or instanceof List<String>. That is the erasure Java engineers remember.

Python goes one step further: nothing is enforced at runtime. def first[T](xs: list[T]) -> T happily accepts a list of mixed items if the checker is not run. Parameterised types cannot be used in isinstance, since isinstance(x, list[int]) raises TypeError.

Variance also looks different. Java uses wildcards at the use site (? extends Animal). Python declares variance on the class, or infers it with the new syntax, and uses Sequence for the read-only case.

So the mental model carries over, with one change: the checker is the only guard.

"When is a type alias worth using?"

A type alias is worth it in two situations. First, when a long type is repeated, because naming it keeps signatures readable and gives one place to change. The new statement also supports recursion, which a plain assignment cannot:

type aliasesruns offline
type Json = dict[str, Json] | list[Json] | str | int | float | bool | None
type Pair[T] = tuple[T, T]
type CustomerId = int

Second, to give a name that says what a value is for, as in CustomerId.

But an alias is only another name, not a new type. A function declared to take a CustomerId will accept any int, including an order id, and the checker will not complain. When mixing them up would be a costly bug, I use NewType("CustomerId", int), which the checker treats as a distinct type, at no runtime cost.

I do not alias everything. A two-word type such as list[str] is clearer written out.

Q119. "TypedDict, dataclass or Pydantic model for a JSON payload — how do you choose?"

Reveal answer

Strong answer The question is whether the data has been validated and whether I need behaviour.

TypedDict describes the keys of a dictionary for the type checker. At runtime it is a plain dict with no check at all. Good for describing a dict you already trust or are passing around. dataclass is a normal class with generated __init__, __eq__ and __repr__: it stores typed fields and nothing checks them at runtime. Good for internal domain objects. Pydantic model validates and converts input when you create it, and reports clear errors. Good at the boundary, where JSON arrives from outside.

My pattern: Pydantic at the edge to parse and validate request and response data, then plain dataclasses (frozen, with slots) inside the domain. TypedDict when I must keep a dict for compatibility, such as a library that expects dicts.

Pydantic also coerces: the string "2" becomes the integer 2 in the default (lax) mode. Use strict mode if you want it to refuse.

Picture it The same bad payload given to all three.

The setup: The payload has qty as the string "two". Each type expects an int.

payloads.py · Python 3.12 (venv)runs offline
from dataclasses import dataclass
from typing import TypedDict
from pydantic import BaseModel, ValidationError

class OrderTD(TypedDict):
    sku: str
    qty: int

@dataclass
class OrderDC:
    sku: str
    qty: int

class OrderPM(BaseModel):
    sku: str
    qty: int

raw = {"sku": "A1", "qty": "two"}
print("TypedDict :", OrderTD(**raw), "<- no check at runtime")
print("dataclass :", OrderDC(**raw), "<- no check at runtime")
try:
    OrderPM(**raw)
except ValidationError as e:
    print("pydantic  :", e.errors()[0]["type"], "-", e.errors()[0]["msg"])
print("coerces '2':", OrderPM(sku="A1", qty="2"))

Make the invisible visible: Run it.

output · Python 3.12runs offline
TypedDict : {'sku': 'A1', 'qty': 'two'} <- no check at runtime
dataclass : OrderDC(sku='A1', qty='two') <- no check at runtime
pydantic  : int_parsing - Input should be a valid integer, unable to parse string as an integer
coerces '2': sku='A1' qty=2

What you see: The TypedDict and the dataclass accepted 'two' silently. Pydantic raised a validation error, int_parsing, saying the string cannot be parsed as an integer. It also converted "2" to 2.

Choosing between them.
OptionPick it whenCost or catch
TypedDicttyping an existing dictno runtime check; no methods
dataclassinternal domain objects, trusted datano validation; hints only
Pydantic modelinput from outside the processslower than a dataclass; coercion rules to learn

Why: The hints in the first two are for the checker only. Data from outside needs a runtime check, and only Pydantic gives you one.

Land it I validate at the boundary with Pydantic, use frozen dataclasses for internal domain values, and keep TypedDict only for describing dicts I cannot avoid.

Likely follow-ups
"Is Pydantic slow?"

It is fast enough for most services, but not free. Version 2 has its core in Rust, and it validates a whole payload in one call. Creating a plain dataclass does no checking at all, so it is always cheaper. The extra time buys validation, conversion and good error messages.

The way I use that fact is to pay for validation once, at the edge. A request arrives, Model.model_validate_json(body) parses and validates in one pass (usually faster than json.loads followed by validation), and inside the service I pass plain dataclasses or the validated model along without validating again.

For code that handles already-validated data in large volumes, such as a batch pipeline between trusted stages, I avoid re-validating each object. model_construct builds a model with no checks, which is only safe for data I already trust.

If parsing speed is the limit, msgspec is a faster alternative for pure decode-and-validate work, with fewer features. I would switch only after a profile (Q104) shows validation is a meaningful share.

"What is strict mode?"

It is a mode in which Pydantic refuses to convert types. The default, lax mode, converts sensible values: the string "2" becomes the int 2, and "true" can become True. In strict mode, those are errors.

turning strict onruns offline
class Order(BaseModel):
    model_config = ConfigDict(strict=True)   # whole model
    qty: int

Order.model_validate({"qty": "2"})           # ValidationError
# or per call: Order.model_validate(data, strict=True)

Why would I want it? Lax mode is friendly for web forms and query strings, where everything arrives as text. For machine-to-machine APIs, a string where an integer belongs usually means a bug in the sender. Strict mode surfaces it at once instead of hiding it.

There is a cost: the sender must follow the contract exactly, so I use strict where I control both sides, and lax where users type the data.

"Can a dataclass validate?"

Yes, by hand. A dataclass does not check values, but I can add checks in __post_init__, which runs right after the generated __init__.

dataclass with an invariantruns offline
@dataclass(frozen=True, slots=True)
class Price:
    amount: int
    def __post_init__(self):
        if self.amount <= 0:
            raise ValueError("amount must be positive")

That is fine for a few invariants in one small class, such as a price that must be positive. It does not convert types and it does not check that amount is actually an int.

For nested data, many fields, or input from outside, hand-written checks grow long and miss cases, and a library is less error-prone. Pydantic also offers pydantic.dataclasses.dataclass, which keeps the dataclass look and adds validation.

My split is: invariants of my own domain objects go in __post_init__, and anything that parses outside data goes through Pydantic.

"What about attrs and NamedTuple?"

They sit between the options, and the table shows how.

TypeValidates at runtimeMutableTypical use
TypedDictNoYes (a dict)Describing a dict you must keep
dataclassNoYes, or frozenInternal domain objects
attrs classYes, with validators and convertersYes, or frozenLibraries wanting more than dataclass
NamedTupleNoNoSmall, cheap, hashable records
Pydantic modelYes, with conversionYes, or frozenData crossing the boundary

attrs is the older, richer relative of dataclasses (dataclasses were modelled on it). It offers validators, converters and more control, and is popular in libraries.

A NamedTuple is a tuple with names, so it is small and hashable. But it is still a tuple: it can be indexed (row[0]) and compared with plain tuples, which can leak into code that should not depend on order (Q38).

Q120. "Any versus object — and why does Any spread through a codebase?"

Reveal answer

Strong answer Both can hold any value, but they mean opposite things to a checker.

object means "some value, and I promise nothing about it". The checker only allows what every object supports, so you must narrow the type (isinstance) before using it. Any means "stop checking". Every attribute access, call or operation on an Any is allowed, and the result is again Any.

That last point is why Any spreads. If a function returns Any and you pass its result around, everything derived from it is also Any, and errors disappear along the whole chain. A single json.loads() (which returns Any) can switch off checking for everything downstream. Worse, if you annotate the receiving variable with a precise type, the checker believes you, even if the data does not match.

Use object when you truly accept anything, and validate before use. Treat Any as a loan: contain it at one boundary, convert to real types there (with Pydantic or checks), and turn on --warn-return-any or --strict to find leaks.

Picture it Using each, and a leak that the checker believes.

any_vs_object.py · checked by mypy 2.4.1runs offline
from typing import Any

def use_any(x: Any) -> None:
    x.whatever()            # accepted: Any switches checking off
    print(x + 1)

def use_object(x: object) -> None:
    x.whatever()            # error: object has no such attribute
    print(x + 1)            # error: no + on object

def leak(data: Any) -> int:
    return data["qty"]      # declared int, but nothing proves it

n = leak({"qty": "three"})  # mypy is happy
reveal_type(n)              # int, but at runtime it is a str

Make the invisible visible: Run mypy.

mypy any_vs_object.pyruns offline
any_vs_object.py:8: error: "object" has no attribute "whatever"  [attr-defined]
any_vs_object.py:9: error: Unsupported operand types for + ("object" and "int")  [operator]
any_vs_object.py:15: note: Revealed type is "int"
Found 2 errors in 1 file (checked 1 source file)

What you see: use_any produced no errors for x.whatever() and x + 1. use_object was rejected twice. leak returned a declared int from an Any, so mypy revealed int for n: at runtime it would be the string "three".

Any: checking switched off

Anything goes, and the result is Any too.

any.pyruns offline
def f(x: Any):
    x.oops()       # accepted
    return x + 1   # accepted

object: prove it first

The checker demands a narrowing check.

object.pyruns offline
def f(x: object):
    if isinstance(x, int):
        return x + 1

The shift: Any says trust me; object says show me.

Why: Any turns the checker off and tells it not to complain; object keeps it on and forces you to prove what the value is.

Land it I use object when I accept anything and must narrow it, treat Any as a leak to contain at the boundary, and use strict flags to find where it escapes.

Likely follow-ups
"How do I narrow an object?"

By proving what it is before using it. The checker tracks the type within each branch, so after a check, the variable has the narrower type inside that branch. There are four common tools.

  1. isinstance: if isinstance(value, str): value.upper(). Inside the branch, value is a str.
  2. match: match value: case int(n): ... or case [first, *_]: ... narrows by shape and type in one step.
  3. Early exit: if value is None: raise ..., after which it is not None for the rest of the function.
  4. Type guards: a function returning TypeIs[Order] (3.13+, or TypeGuard in older versions) tells the checker that a True result means the value is an Order.

Use a type guard for checks too long to write inline, for example "this dict has the keys of an order". Be careful that the guard actually checks what it claims, since the checker trusts it. A wrong guard is as bad as a wrong cast.

"What mypy options find Any?"

Several options find Any, and they catch different leaks. The ones I switch on first:

mypy flags for finding Anyruns offline
mypy --warn-return-any src/        # function returns Any but declares a type
mypy --disallow-untyped-defs src/  # every function must have hints
mypy --disallow-any-generics src/  # list, dict with no parameters
mypy --strict src/                 # all of these and more

--warn-return-any catches the most common leak: return json.loads(text) in a function declared to return dict[str, str]. With --strict this chapter's example gave Returning Any from function declared to return dict[str, str] (Q123).

--disallow-any-generics catches a bare list or dict hint, which means list[Any]. --disallow-any-explicit bans writing Any, which is noisy, so I keep it for a few core packages.

In pyright, strict mode reports the equivalent "unknown" types. I enable flags one at a time per package, so the error count stays manageable. A bare return data from an untyped helper shows up this way too.

"Is Any ever right?"

Yes, in a few honest cases, as long as I choose it deliberately and keep it small.

One is genuinely dynamic code, such as a plugin that receives arbitrary keyword arguments, or a function that accepts any JSON for storage. Another is migration: marking a hard part Any for now lets the rest be checked, and I come back later (Q125). A third is a pass-through, where the function does not look at the value. A wrapper with *args: Any, **kwargs: Any only forwards, and when I can do better, ParamSpec (Q121) keeps the signature.

The test I apply is: does this Any flow into code that then uses the value? If the value only passes through, it is harmless. If someone later calls methods on it, the leak spreads.

I prefer object over Any when I mean "anything", because it forces a check before use. And I leave a comment where an Any is deliberate, so a later reader does not think it was forgotten.

"What about cast and # type: ignore?"

They are promises. They tell the checker "trust me", and the checker cannot verify them. That makes them similar to Any: they switch checking off at one point.

cast does nothing at runtimeruns offline
user = cast(User, data)   # no check, no conversion; data is unchanged
x = parse(raw)  # type: ignore[arg-type]   # silence one specific error

cast only changes what the checker believes. If data is not a User, the code fails later at some unrelated line.

I use them under three rules. First, give a reason in a comment, so a reviewer can judge it. Second, name the error code, as # type: ignore[arg-type], so other errors on the same line still show. Third, prefer a narrowing check (isinstance or a guard) when possible, because it satisfies the checker and also protects at runtime.

Turn on warn_unused_ignores, so an ignore that no longer silences anything is reported and removed.

Q121. "How do you type a decorator properly with ParamSpec and Concatenate?"

Reveal answer

Strong answer A naive decorator typed as Callable[..., Any] -> Callable[..., Any] compiles but erases the signature: after decoration, the checker no longer knows the parameters or the return type, so wrong calls pass silently.

ParamSpec captures "whatever parameters the wrapped function has" as a single placeholder P. The decorator is typed Callable[P, R] -> Callable[P, R], and the wrapper takes *args: P.args, **kwargs: P.kwargs. The checker then knows the decorated function has exactly the original signature. Concatenate is for decorators that add or remove a leading parameter. Callable[Concatenate[Db, P], R] -> Callable[P, R] says: "I take a function whose first parameter is a Db and return one without it" (the decorator supplies the database).

Use functools.wraps too, so name and docstring survive at runtime. In 3.12 you can write def timed[**P, R](fn: Callable[P, R]) -> Callable[P, R] with the bracket syntax.

Picture it Two decorators, one preserving the signature and one removing a parameter, checked by mypy.

paramspec.py · checked by mypy 2.4.1runs offline
from typing import reveal_type
import functools, time
from typing import Callable, Concatenate, ParamSpec, TypeVar

P = ParamSpec("P"); R = TypeVar("R")

def timed(fn: Callable[P, R]) -> Callable[P, R]:
    @functools.wraps(fn)
    def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
        t = time.perf_counter()
        try:
            return fn(*args, **kwargs)
        finally:
            print(f"{fn.__name__} took {(time.perf_counter()-t)*1000:.2f} ms")
    return wrapper

class Db: ...

def with_db(fn: Callable[Concatenate[Db, P], R]) -> Callable[P, R]:
    def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
        return fn(Db(), *args, **kwargs)
    return wrapper

@timed
def price(sku: str, qty: int = 1) -> float:
    return 2.5 * qty

@with_db
def load(db: Db, order_id: int) -> str:
    return f"order {order_id}"

reveal_type(price)
reveal_type(load)
price("A1", qty="x")       # error caught thanks to ParamSpec
load("not-an-int")         # error caught
print(price("A1", qty=2), load(7))

Make the invisible visible: Run mypy.

mypy paramspec.pyruns offline
paramspec.py:32: note: Revealed type is "def (sku: str, qty: int =) -> float"
paramspec.py:33: note: Revealed type is "def (order_id: int) -> str"
paramspec.py:34: error: Argument "qty" to "price" has incompatible type "str"; expected "int"  [arg-type]
paramspec.py:35: error: Argument 1 to "load" has incompatible type "str"; expected "int"  [arg-type]
Found 2 errors in 1 file (checked 1 source file)

What you see: reveal_type(price) shows def (sku: str, qty: int =) -> float: the original signature survived @timed. load shows def (order_id: int) -> str: the Db parameter is gone, as with_db promised. Both wrong calls were reported with the real parameter names.

Naive typing

Everything becomes Any.

naive.pyruns offline
def timed(fn: Callable[..., Any]
          ) -> Callable[..., Any]:
    ...
# price("A1", qty="x") passes

ParamSpec typing

Parameters and result are kept.

typed.pyruns offline
def timed(fn: Callable[P, R]
          ) -> Callable[P, R]:
    ...
# price("A1", qty="x") fails

The shift: A typed decorator promises the checker that the function keeps its shape; the naive one throws the shape away.

Why: Without ParamSpec every decorated function in a codebase quietly becomes untyped, and the number of unchecked calls grows with each decorator.

Land it I type decorators with ParamSpec and a return TypeVar so the signature survives, use Concatenate when the decorator injects a first argument, and verify with reveal_type.

Likely follow-ups
"What are P.args and P.kwargs?"

They are the two halves of one captured parameter list. If a function is def send(to: str, retries: int = 3), the ParamSpec P stands for "(to: str, retries: int = 3)" as a unit. P.args is the type of the positional arguments in that list, and P.kwargs is the type of the keyword arguments.

a typed decoratorruns offline
def timed[**P, R](fn: Callable[P, R]) -> Callable[P, R]:
    @wraps(fn)
    def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
        return fn(*args, **kwargs)
    return wrapper

They must always be used together, as *args: P.args, **kwargs: P.kwargs, and only in a function that has P in scope. Using one without the other is an error.

The benefit appears at the call site: after decoration, send(to=5) is reported as a wrong type, and the editor still shows the real parameter names. Without ParamSpec, both would be lost.

"How do I type a decorator with arguments, such as @retry(times=3)?"

It takes three nested layers, and each layer is typed on its own. Take @retry(times=3).

  1. Outer function: retry(times: int) takes the settings and returns the decorator. Its return type is Callable[[Callable[P, R]], Callable[P, R]], which reads "a function that takes a function and returns one with the same signature".
  2. Decorator: decorator(fn: Callable[P, R]) -> Callable[P, R], exactly the simple case.
  3. Wrapper: wrapper(*args: P.args, **kwargs: P.kwargs) -> R with @wraps(fn) on it.

With the 3.12 syntax, I declare the type parameters once on the outer function: def retry[**P, R](times: int) -> Callable[[Callable[P, R]], Callable[P, R]]:. The inner functions then use the same P and R.

The easy mistake is to forget the outer layer's return type, so the checker sees the decorator as returning Any. I use reveal_type(decorated_function) to confirm the signature survived.

"What about async functions?"

Treat the function as returning an awaitable, and make the wrapper async too. The input type is Callable[P, Awaitable[R]] (or Callable[P, Coroutine[Any, Any, R]] if I want to insist on coroutines), and the wrapper is an async def that awaits the call.

typed async decoratorruns offline
def logged[**P, R](fn: Callable[P, Awaitable[R]]) -> Callable[P, Awaitable[R]]:
    @wraps(fn)
    async def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
        log.info("calling %s", fn.__name__)
        return await fn(*args, **kwargs)
    return wrapper

The common bug is a plain def wrapper around an async function. It calls fn(...) and returns the coroutine, so any timing or logging around the call measures only creating the coroutine, not the work.

If the decorator has to work on both sync and async functions, I write two overloads or two decorators. One function that tries to handle both is hard to type.

"Is typing decorators worth the effort?"

For decorators used widely, yes. For a one-off, a lighter approach is fine.

The reasoning is about reach. A decorator such as @retry, @cached or @require_role may sit on a hundred functions. If it is typed as Callable[..., Any], all hundred lose their signatures at once. Wrong argument names, wrong types and wrong return types are no longer caught, and autocomplete in the editor disappears. That silent loss is the same kind of leak as Any (Q120).

Typing it correctly costs about five lines, once. After that, every use is checked for free.

For a decorator used on one function in one script, I accept Callable[..., Any] or skip the hints, since the effort does not repay itself.

A good habit is to put a small test or a reveal_type line next to the decorator, which shows the checker's result, so a later change that breaks the typing is noticed. I also keep @wraps so the name and docstring survive at runtime.

Q122. "What changed about annotations in 3.14 (PEP 649 deferred evaluation)?"

Reveal answer

Strong answer Before 3.14, annotations were evaluated immediately, when a function or class was defined. A reference to a name that does not exist yet raised NameError, so you had to write the hint as a string ("Customer") or add from __future__ import annotations.

In 3.14 (PEP 649 and 749) annotations are evaluated lazily: Python stores a small function that computes them, and runs it only when someone reads them. A class can refer to another class defined further down with no quotes and no future import. Forward references just work, and programs that never read annotations do not pay for them at import time.

The new annotationlib module lets tools read annotations in three formats: real values (VALUE), placeholder objects for undefined names (FORWARDREF), or source strings (STRING). Libraries such as Pydantic and dataclasses use it.

Practical effects: remove quotes where they are no longer needed (but keep them if the code must run on 3.13 or older), and code that inspected __annotations__ early may need annotationlib.get_annotations.

Picture it A class that refers to classes defined below it.

deferred.py · Python 3.14runs offline
import annotationlib

class Order:
    customer: Customer          # defined further down: no quotes, no __future__
    def total(self) -> Money: ...

try:
    print("evaluated early:", Order.__annotations__)
except NameError as e:
    print("evaluated early -> NameError:", e)

class Customer: ...
class Money: ...

print("evaluated late :", Order.__annotations__)
print("FORWARDREF     :", annotationlib.get_annotations(Order, format=annotationlib.Format.FORWARDREF))
print("STRING         :", annotationlib.get_annotations(Order, format=annotationlib.Format.STRING))

Make the invisible visible: Run it.

output · Python 3.14runs offline
evaluated early -> NameError: name 'Customer' is not defined
evaluated late : {'customer': <class '__main__.Customer'>}
FORWARDREF     : {'customer': <class '__main__.Customer'>}
STRING         : {'customer': 'Customer'}

What you see: Reading the annotations early raised NameError: name 'Customer' is not defined, because the evaluation happens when you ask, not at definition. The class definition itself did not fail. After Customer exists, the same read returns the real class. The STRING format returns the source text 'Customer' without evaluating anything.

Why: Evaluating on demand removes the ordering problem and the import cost, and gives tools a choice of how much to resolve.

Land it I say 3.14 evaluates annotations lazily, so forward references need no quotes or future import, and tools should read them through annotationlib.get_annotations with the format they need.

Likely follow-ups
"Should I still use from __future__ import annotations?"

If the code must run on 3.13 or older, yes. On 3.14 and newer it is not needed for forward references, because the new default already delays evaluation.

The import is not the same thing as the new behaviour, though. from __future__ import annotations (PEP 563) turns every annotation into a string at compile time. The new 3.14 behaviour (PEP 649) keeps real expressions and evaluates them later, on demand, with the right scope. The new one is better because tools get real objects, not text.

With the import still present on 3.14, that module keeps the old string behaviour, so a library reading __annotations__ gets text and must evaluate it. The import is also expected to be phased out in the long run (check the release notes of your version), so I would not add it to new 3.14-only code.

My rule: libraries that support old versions keep it. Applications that only run on 3.14 drop it and remove the quotes.

"Why did the old string-based approach cause trouble?"

Strings lose their scope. A string annotation such as "Customer" is just text. To turn it back into a class, a tool has to evaluate it later, and it has to guess in which namespace to do that. Usually it uses the module's globals. That fails in two common cases.

First, a class defined inside a function, which is not in the module's globals, so typing.get_type_hints raises NameError. Second, a name imported only under if TYPE_CHECKING:, which exists for the checker but not at runtime.

That matters because Pydantic and FastAPI need real types to build validators and API documents. Users saw "class not fully defined" errors and had to call rebuild methods.

Lazy evaluation in 3.14 stores the code that computes the annotation together with its original scope, so the name is looked up where it was written. Forward references to later names work, and the tool can ask for a placeholder when a name is still missing, which is the next question.

"What is FORWARDREF format for?"

It is for tools that want as much information as possible without crashing. annotationlib.get_annotations can return annotations in three formats, and this run shows them on a class that refers to Customer before that class exists:

q122_forwardref.py outputruns offline
VALUE before Customer exists: name 'Customer' is not defined
FORWARDREF (before): {'customer': ForwardRef('Customer', is_class=True, owner=<class '__main__.Order'>)}
STRING (before): {'customer': 'Customer'}
VALUE (after): {'customer': <class '__main__.Customer'>}

VALUE gives real objects and raises NameError if a name is missing. STRING gives the source text. FORWARDREF gives real objects where they exist and a ForwardRef placeholder where they do not.

A serialiser or validator can use FORWARDREF to proceed with the fields it knows and complain only about the one that is missing, with a clear message. After the missing class is defined, the same call with VALUE works.

"Does this affect runtime cost?"

Mostly in your favour. In 3.14 the module does not build the annotation objects at import time. Python compiles each annotation into a small function that is run only when someone reads __annotations__ (or calls get_annotations), and then the result is cached.

Before, every def and class statement built its annotation objects during import, such as list[dict[str, int]], which is real work and memory even if nobody reads them. In a large typed codebase that is a visible part of start-up time.

The saving is not universal. Dataclasses read annotations when a class is created, to find the fields. Pydantic and FastAPI read them to build validators. For those, the work moves but does not disappear. The code object for each annotation is also still compiled and stored in the .pyc file.

So I do not expect a dramatic change. I expect a modest import-time gain in plain typed code, and no change at runtime per call.

Q123 · Scenario. "mypy passes, yet production crashes on None. How did that happen?"

Reveal answer

Strong answer A passing checker means "no error was found in what was checked", not "no error exists". The usual causes, in order of frequency:

  1. Any leaked in: a value from json.loads, an untyped library, or an unannotated function is Any, so everything derived from it is unchecked (Q120).
  2. Untyped function bodies: by default mypy skips the inside of functions without annotations.
  3. cast or # type: ignore: a human promise that overrides the checker.
  4. Wrong declaration: a function declared to return dict[str, str] actually returns whatever the JSON contains. The checker believes the declaration.
  5. Data at the boundary: hints do not validate input, so a null in the payload passes through.

The fix is both stricter configuration and validation at the boundary. Turn on --strict (or at least --warn-return-any and --disallow-untyped-defs) and parse external data with Pydantic so the declared types are true.

Types and tests catch different bugs; neither replaces the other.

Picture it A function that mypy accepts and that crashes on real data.

none_gap.pyruns offline
from typing import Any, cast
import json

def load_user(raw: str) -> dict[str, str]:
    return json.loads(raw)               # json.loads returns Any: nothing checked

def name_len(raw: str) -> int:
    user = load_user(raw)
    return len(user["name"])

def untyped(x):                          # no annotations: body is not checked by default
    return x.strip()

def lookup(d: dict[str, int], k: str) -> int:
    return cast(int, d.get(k))           # ❌ cast silences the checker

print(untyped(5) if False else "defined")
print(name_len('{"name": null}'))        # mypy passes; crash at runtime

Make the invisible visible: Run mypy normally, run the program, then run mypy in strict mode.

mypy none_gap.pyruns offline
Success: no issues found in 1 source file
python none_gap.py · Python 3.12 (last lines)runs offline
defined
Traceback (most recent call last):
  File "/home/iam100god/Desktop/AI_COURSE/code/e19-python-deep-dive/E/typing/none_gap.py", line 18, in <module>
    print(name_len('{"name": null}'))        # mypy passes; crash at runtime
          ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/iam100god/Desktop/AI_COURSE/code/e19-python-deep-dive/E/typing/none_gap.py", line 9, in name_len
    return len(user["name"])
           ^^^^^^^^^^^^^^^^^
TypeError: object of type 'NoneType' has no len()
mypy --strict none_gap.pyruns offline
none_gap.py:5: error: Returning Any from function declared to return "dict[str, str]"  [no-any-return]
none_gap.py:11: error: Function is missing a type annotation  [no-untyped-def]
Found 2 errors in 1 file (checked 1 source file)

What you see: Default mypy said Success. The program crashed with TypeError: object of type 'NoneType' has no len(), because json.loads returned Any and the function declared a type the data did not meet. Strict mode flagged two places: the Any returned from a typed function, and the unannotated function. It did not flag the cast line, which I wrote to silence the checker: reviews must catch those.

Why: The checker trusts declarations. The gap sits where untyped data meets a typed declaration, so I validate there.

Land it I explain that a passing checker only covers what it can see, so Any, untyped functions, casts and unvalidated input create gaps, and I close them with strict settings and Pydantic validation at the boundary.

Likely follow-ups
"Which mypy settings would you turn on first?"

I start with the settings that close the biggest gaps at the lowest cost, in this order.

mypy.ini starting pointruns offline
[mypy]
warn_return_any = True
warn_unused_ignores = True
check_untyped_defs = True

[mypy-billing.*]
disallow_untyped_defs = True

warn_return_any catches the leak from json.loads and untyped libraries. check_untyped_defs makes mypy look inside functions that have no hints, which it skips by default. warn_unused_ignores reports ignores that no longer hide anything. And disallow_untyped_defs, set per package, requires full hints in new or cleaned-up code.

Implicit optional (a default of None making a parameter optional) is off by default in current mypy, so I do not need a flag for it.

The goal is to move toward --strict one package at a time, rather than turning it on everywhere and drowning in errors.

"How do I stop None bugs specifically?"

The biggest help is to make the possibility of None visible in the type, so the checker forces every caller to handle it.

  1. Declare it: a function that may find nothing returns User | None. The checker then reports user.name on that result as an error, until the caller checks.
  2. Narrow it: if user is None: raise NotFound(uid), and below that line the type is plain User.
  3. Avoid it where possible: return an empty list instead of None, or raise an error, so callers have nothing to forget.
  4. Watch the sources: dict.get returns an optional value, and re.match returns None when nothing matches. Both are common production crashes.

I do not use assert x is not None as the only guard in production code, because Python can strip asserts with the -O flag and the check then disappears. For a real error I raise one. And I validate JSON at the boundary (Pydantic), since a null from outside never passes through the checker.

"Does this mean typing is not worth it?"

No. It is worth a lot, but it is one layer, and each layer catches a different kind of problem. Saying it is useless because it missed one bug is as wrong as trusting it fully.

LayerCatchesMisses
Type checkerWrong types, missing None handling, renamed fieldsAnything through Any, casts, outside data
TestsWrong behaviour on the cases writtenCases nobody thought of
Boundary validationBad or null values from outsideLogic errors inside
MonitoringWhat really happens in productionNothing before release

Figure 19.19 of this chapter shows the same idea as a picture of which layer catches what.

The checker catches a large class of mistakes cheaply, and it does so on every commit, which tests rarely match. So the conclusion is to close its known gaps (Any, ignores, boundaries) and keep the other layers, not to drop typing.

"How do I audit existing cast and ignore uses?"

I make them countable and visible, so that they cannot pile up unnoticed.

counting the escape hatchesruns offline
grep -rn "type: ignore" src | wc -l
grep -rnE "\bcast\(" src | wc -l
grep -rnE "\bAny\b" src | wc -l

With three numbers, I can track them per week and watch the trend. A rising count is a smell, a falling one is progress.

Then three rules. First, every new cast or ignore needs a comment with the reason, checked in code review. Second, ignores name the error code (ignore[attr-defined]), so they hide one thing only. Third, warn_unused_ignores = True makes the build fail when an ignore no longer hides anything, so stale ones get deleted automatically.

For the old ones, I sort by package. The hot ones in the core modules get fixed first. An ignore that hides a real bug is worth an hour; one on a rarely changed edge can wait.

Q124. "mypy versus pyright versus ty — how do you choose?"

Reveal answer

Strong answer All three read your hints and report errors. They differ in age, speed, strictness and how they fit your tools.

Static type checkers.
CheckerPick it whenCost or catch
mypythe reference checker; large existing codebases, plugin ecosystem (Django, SQLAlchemy, Pydantic plugins)slower on big projects (it has incremental caching and a daemon); inference is conservative
pyrightfast, strict by default; best editor integration through Pylance in VS Codewritten in TypeScript so needs Node.js; behaviour differs slightly from mypy
ty (Astral)very fast, from the makers of Ruff and uv; promising for new projectsbeta/preview at the time of writing (I ran version 0.0.109); rules and output still change

My choice: whatever the team can enforce in CI and everyone sees in the editor. Mixing is common: pyright in the editor, mypy in CI. I would try ty on a side branch and watch it, and not make it the only gate until it is stable.

The main point is not the brand but running one checker consistently, in CI, as a blocking step, with a baseline for existing errors.

Picture it The same bug file given to mypy and to ty.

mypy find_rule.py · mypy 2.4.1runs offline
find_rule.py:13: error: Item "None" of "Rule | None" has no attribute "amount"  [union-attr]
Found 1 error in 1 file (checked 1 source file)
uvx ty check find_rule.py · ty 0.0.109 (preview)runs offline
error[missing-union-attribute]: Attribute `amount` is not defined on `None` in union `Rule | None`
  --> find_rule.py:13:12
   |
13 |     return find_rule(code).amount      # ❌ None is possible
   |            ^^^^^^^^^^^^^^^^^^^^^^

What you see: Both found the same bug on line 13: Rule | None has no attribute amount. ty prints the source line with a pointer, in the style of Rust compiler messages. I did not run pyright, which is not installed here; the description above comes from its documentation.

Why: On clear bugs the checkers agree. They differ on edge cases of inference, so I judge them on my own codebase, not on benchmarks.

Land it I choose the checker the team will actually enforce in CI and see in the editor, usually mypy or pyright today, and watch ty as a fast newcomer still in preview.

Likely follow-ups
"Why would I run two checkers?"

Because feedback timing and the enforced gate are separate needs. In the editor, I want an answer as I type, within a second. In CI, I want one trusted rule that every merge must pass.

Pyright, through Pylance in VS Code, gives instant feedback in the editor. Mypy, with its plugin ecosystem (Django, SQLAlchemy, Pydantic), may be the checker the project's configuration and plugins were written for, so it stays as the CI gate. The team gets fast hints from one and the final verdict from the other.

The cost is disagreement. They differ in how they infer types for empty containers, how they narrow in unusual branches and how they treat some unions. Code that is clean in one may show an error in the other, and developers lose time arguing with the wrong one.

So I pick one as the authority, usually the one in CI, and treat the other as advice. If the disagreements become frequent, I move everything to a single checker. Two gates are worse than one.

"How do checkers handle libraries without hints?"

The checker needs type information for the library. It gets it from two places.

First, the library itself ships hints and a marker file named py.typed (PEP 561). Then the checker reads the code directly. Modern libraries such as Pydantic and FastAPI do this.

Second, separate stub packages, such as types-requests, which hold only hints and are installed next to the library. The standard library's hints come from typeshed, bundled with the checkers. For a missing stub, mypy often tells you the package name to install.

When there is neither, the import is treated as Any. mypy reports "missing library stubs" and many people silence it with ignore_missing_imports. I allow that for one named module, not globally, since the global setting hides typos in import names too. Then everything from that library is Any, and we are back to the leak in Q120.

The fix is a small wrapper around the library with typed signatures, so the rest of the code never sees Any.

"Are Ruff and the type checkers related?"

They are different kinds of tools, and they complement each other. Ruff is a linter and formatter. It applies hundreds of rules to each file's syntax: unused imports, style, common bug patterns, import sorting. It does not build a full model of types across files, so it cannot tell you that you passed a str where an int belongs.

A type checker does exactly that. It infers types, follows them across modules and reports mismatches. It is slower to run and needs the hints.

ty is a type checker from the same company as Ruff and uv (Astral), built for speed. So the relation is the company and the design values, not the job.

In practice I run both kinds. Ruff runs in a second on every save and in pre-commit. The type checker runs in CI and in the editor.

A few Ruff rules touch typing (flagging outdated typing.List imports, say), but they check how hints are written, not whether they are correct. That belongs to the checker.

"How do I evaluate a new checker?"

I run an experiment, not an opinion contest, and I answer four questions with data.

  1. How many findings, and how many are real? Run it on the codebase, take a random sample of 30 findings and sort them into real bugs, noise and "correct but different from the other checker". The ratio tells me about quality.
  2. How fast? Time a full run and a re-run after a one-file change. For big projects, the incremental time decides daily use.
  3. Does it understand my libraries? Check how it handles the main ones (Django, SQLAlchemy, Pydantic, FastAPI), since plugin support differs.
  4. Is it stable? For a preview tool such as ty, check how often rules and output change between releases.

I run the new tool in a side CI job that does not block merges, and compare it for a few weeks. Only if it wins on those points, and the team can use it in the editor, do I make it the gate.

Q125 · Design. "Introduce typing to a 200,000-line untyped codebase without stopping feature work."

Reveal answer

Strong answer I make it gradual, enforced for new code first, and measured.

  1. Install the checker in CI with a baseline: run it, record today's error count per module, and make CI fail only on new errors. Nothing existing blocks anyone.
  2. Strict for new code: new modules and files touched in a pull request must be fully annotated (disallow_untyped_defs per module, via config overrides).
  3. Type the boundaries first: public APIs, models, the data layer and the functions most called. Typing the centre of the call graph makes the checker useful everywhere.
  4. Replace Any and dict-shaped data: dataclasses or Pydantic models for payloads, so types are true, not wishes.
  5. Automate the boring part: tools such as MonkeyType (records types at runtime) or pyrefly infer and autotyping generate first-draft hints, which humans review.
  6. Ratchet: track the percent of typed functions and the count of Any and ignore weekly; raise the strictness per package as it reaches zero errors.

I would assign a small rotation, say 10 percent of each sprint, and agree on conventions in a short document (when to use Protocol, never bare Any, how to annotate callbacks).

Success is not 100 percent coverage; it is that the checker is trusted and catches real bugs before production.

Picture it A configuration that is strict only where the team has earned it. This is an illustrative configuration; I did not apply it to a real 200,000-line project.

pyproject.toml (illustrative)runs offline
# illustrative
[tool.mypy]
python_version = "3.12"
warn_unused_ignores = true
warn_return_any = true
ignore_missing_imports = false

# default: lenient for the legacy code
[[tool.mypy.overrides]]
module = "legacy.*"
ignore_errors = true            # baseline: remove one package at a time

# strict where the team has earned it
[[tool.mypy.overrides]]
module = ["pricer.money", "pricer.rules", "pricer.service"]
disallow_untyped_defs = true
disallow_any_generics = true
strict_equality = true
progress chart the team keeps (illustrative numbers)runs offline
# illustrative
week   typed functions   Any/ignore   mypy errors (baseline 3,412)
  0        4 %              n/a          3,412
  8       19 %              412          3,380  (new code clean)
 16       41 %              260          2,100
 32       78 %              120            540
 52       93 %               40              0   -> turn on --strict globally

Why: A baseline plus a ratchet turns a huge, risky migration into small daily steps that never block a release.

Land it I add the checker to CI with a baseline, require strict typing for new and touched code, type the boundaries first, generate first drafts with tooling, and ratchet strictness up as modules reach zero errors.

Likely follow-ups
"How do you get the team to cooperate?"

By making it cheap and visible, because a mandate with no help produces Any everywhere. Four things matter.

First, speed. A pre-commit hook or editor check that returns in a few seconds gets used. One that takes five minutes gets bypassed. Second, help with the boring part: auto-generated first drafts of hints (MonkeyType, autotyping) so nobody types out 3,000 signatures from scratch. Third, a short style guide: when to use a Protocol, never write a bare Any without a comment, how to annotate a callback. One page, with examples from our own code.

Fourth, show the benefit early. The first time the checker catches a real bug, such as a possible None that was about to reach production, I share it in the team channel with the diff. One concrete save convinces more than a policy document.

I also keep the rotation small and fair, about 10 percent of each sprint, so typing is a steady habit and not a heroic month that burns people out.

"What if mypy is too slow on 200,000 lines?"

I would first make mypy faster, and only then think about replacing it.

  1. Use the cache and the daemon: mypy keeps results in a cache folder, so later runs check only what changed. The daemon, started with dmypy run -- src, keeps the analysis in memory, so a re-check after a one-file edit takes a second or two, not a full run. In CI, restore the cache folder between runs.
  2. Split the work: check only changed files with the daemon in pre-commit, and the whole project in CI as the real gate.
  3. Trial another checker: pyright is often faster on big projects, and ty is very fast but in preview. I try one on a side branch and compare findings, as in the earlier question.

Cutting the scope also helps: exclude generated code and vendored folders. A check that takes seconds is used every day; one that takes minutes is not, and then the types drift.

"Where does runtime validation fit in?"

At the boundaries, as the fourth step of the plan. Types make the inside of the program consistent, and validation makes the outside honest. The two are needed together, because a hint is only a promise about the data.

Take a function annotated to return Order, built from a JSON body. If I write Order(**json.loads(body)) and a field is null, the checker is satisfied, and the bug appears three calls later. With Pydantic, the body is parsed through the model, and bad data fails there with a clear message:

validate at the edgeruns offline
order = Order.model_validate_json(body)   # raises ValidationError on null qty
process(order)                            # from here on, the types are true

After that line, the declared types are facts, not wishes, so the checker's results mean something. That is why I do boundaries early in the migration: typing the inside of a service that reads unvalidated data gives a false sense of safety.

Inside the service, I do not validate again, since the cost would repeat for nothing.

"How do you handle third-party libraries without stubs?"

I contain them. The goal is that the rest of the code never sees Any coming from a library with no hints.

  1. Look for stubs: install the types-* package if one exists, or a newer version of the library that ships py.typed.
  2. Write small local stubs: for the few functions we use, a .pyi file with the signatures in a stubs/ folder, and point the checker at it (mypy_path = stubs). Ten lines are often enough.
  3. Wrap it: one module, for example billing_client.py, calls the library and returns typed values or Pydantic models. The rest of the code imports only the wrapper.

The wrapper is the best of the three, because it also gives me one place to add retries, logging and tests, and one place to change if the library is replaced.

For a library used once, I allow ignore_missing_imports for that single module and keep a comment. A full wrapper is for libraries that spread through the code.

Drill · Packaging and environments

These questions test whether a deploy would be the same tomorrow as today: environments, pyproject.toml, lock files, wheels and release pipelines.

Q126. "What is a virtual environment, physically?"

Reveal answer

Strong answer It is a folder, nothing more. Inside: a file pyvenv.cfg, a bin/ directory containing a python that is a symbolic link to a real interpreter, and lib/python3.x/site-packages/ where installed packages go.

How does it work? When Python starts, it looks for pyvenv.cfg next to the executable (or one level up). If it finds it, it sets sys.prefix to the venv folder, while sys.base_prefix still points at the real installation. The site module then adds the venv's site-packages to the import path instead of the system one.

The activate script is only a convenience: it puts the venv's bin first on PATH so that typing python finds the venv's link. You can skip activation completely and run .venv/bin/python directly, which is what I do in scripts, CI and services.

Because it is just a folder with absolute paths inside some files, a venv is not relocatable: copy it to another path or machine and it breaks. Recreate it from the lock file instead.

Picture it The course project's own virtual environment, inspected.

Make the invisible visible: Look at the config file, the links and the prefixes.

shell session · Python 3.12 course venvruns offline
$ cat .venv/pyvenv.cfg
home = /usr/bin
implementation = CPython
uv = 0.12.5
version_info = 3.12.3
include-system-site-packages = true

$ ls -l .venv/bin/python*
lrwxrwxrwx /home/iam100god/Desktop/AI_COURSE/.venv/bin/python -> /usr/bin/python3
lrwxrwxrwx /home/iam100god/Desktop/AI_COURSE/.venv/bin/python3 -> python
lrwxrwxrwx /home/iam100god/Desktop/AI_COURSE/.venv/bin/python3.12 -> python

$ ls .venv/lib/python3.12/ ; ls .venv/lib/python3.12/site-packages | head -3
site-packages
6ec57f84c680d3a3778b__mypyc.cpython-312-x86_64-linux-gnu.so
accelerate
accelerate-1.15.0.dist-info

sys.prefix      = /home/iam100god/Desktop/AI_COURSE/.venv
sys.base_prefix = /usr

What you see: pyvenv.cfg records which interpreter (home = /usr/bin), its version, and the flag include-system-site-packages = true. The python in bin/ is a symlink to /usr/bin/python3; the others link to that. sys.prefix is the venv; sys.base_prefix is /usr.

Java · dependencies per project

Maven or Gradle downloads jars into a shared cache and builds a classpath for each project.

shellruns offline
# one shared cache for all projects
~/.m2/repository/...
# classpath built per build
mvn dependency:build-classpath

Python · one environment folder

Packages are installed into a folder that belongs to the project.

shellruns offline
.venv/
  pyvenv.cfg
  bin/python -> /usr/bin/python3
  lib/python3.12/site-packages/
    requests/  pydantic/ ...

The shift: Java shares one jar cache and computes a classpath per build; Python installs a separate copy of each package into each environment folder.

Why: Isolation here is only about which folder is searched for imports. A venv does not isolate the interpreter itself, the operating system or native libraries.

Land it I explain a venv as a folder with pyvenv.cfg, a symlink to the interpreter and its own site-packages, where activation only edits PATH, and I recreate it from the lock file rather than copying it.

Likely follow-ups
"What does include-system-site-packages = true mean?"

It means the venv can also import packages installed in the system Python, so the isolation is weaker. The default for a new venv is false, and I keep it false.

The setting is one line in pyvenv.cfg. When it is true, the site module puts the venv's site-packages on the import path first and the system one after it. A package missing from the venv is then found in the system folder without any warning.

q126_venv.py outputruns offline
home = /usr/bin
include-system-site-packages = false
version = 3.12.3

The trap is that code works on your laptop because the system happens to have the package, then fails in a clean image where it does not. The lock file no longer describes what runs. In production I want false, so the venv contains exactly what the lock file says.

"Why not install everything into the system Python?"

Because the system Python belongs to the operating system, and every project shares it. Three things go wrong.

  1. Version clashes: project A needs requests 2.28 and project B needs 2.32. The system folder holds only one version of a package, so one project loses.
  2. Breaking the OS: on many Linux distributions, system tools such as package managers and installers are written in Python and use the system packages. Upgrading one of those packages with pip can break them. Recent distributions refuse the install and print an "externally managed environment" error for this reason.
  3. No record: nothing says which packages your project needs, so a new machine cannot be rebuilt.

A venv costs a few megabytes and removes all three problems. I treat the system Python as read-only and never run sudo pip install.

"Is a Docker image a replacement for a venv?"

For deployment, an image gives stronger isolation than a venv, because it isolates the whole file system: system libraries, the Python build and the packages. A venv isolates only Python packages. They are not rivals, though, so I often use both.

Inside the image I still create a venv at /app/.venv. The reason is a multi-stage build. The first stage has compilers and runs uv sync to fill the venv. The final stage starts from a slim base and copies only that one folder, so the image has no build tools and is smaller. Because the path is the same in both stages, the absolute paths inside the venv stay valid.

A venv also keeps the application's packages apart from whatever the base image installed for its own use.

For development on a laptop, a venv is lighter and faster than a container, so I use that. Image for shipping, venv for working and for filling the image.

"What does uv change here?"

uv changes the speed and the number of tools, not what a venv is. uv venv creates the same folder with pyvenv.cfg, a bin/python link and a site-packages, and any other tool can use it.

What is different is how it fills the folder. uv keeps one global cache of unpacked packages and links the files into each venv instead of copying them. Installing a package you already used in another project takes milliseconds and no extra disk space. Resolving versions is also written in Rust and is much faster than pip's resolver, which matters most in CI.

uv can also download a specific interpreter, for example uv python install 3.14, so the venv no longer depends on whatever Python the machine has. uv sync creates the venv if it is missing and makes it match the lock file.

My habit: do not activate anything, just run uv run pytest or .venv/bin/python. It works the same on a laptop and in CI.

Q127. "What goes in pyproject.toml, and what is a build backend?"

Reveal answer

Strong answer pyproject.toml is the single configuration file for a Python project. It has three kinds of content.

[project] (PEP 621): the metadata: name, version, description, supported Python versions (requires-python), dependencies, optional dependency groups, entry-point scripts. [build-system] (PEP 517 and 518): which tool builds the package: a list of requires and a build-backend. [tool.xxx]: settings for tools such as Ruff, pytest, mypy, uv.

A build backend is the program that turns your source tree into a wheel and an sdist: hatchling, setuptools, flit-core, pdm-backend, or maturin for Rust extensions. A frontend (pip, uv build, python -m build) reads [build-system], creates an isolated environment with the backend, and calls it. That separation means you can switch backend without changing how users install.

My default for a pure-Python library: hatchling or setuptools with a src layout; for an application, [project] plus a lock file and no build step at all.

Picture it A real minimal library and what building it produced.

pyproject.tomlruns offline
[project]
name = "demo-lib"
version = "0.1.0"
description = "Tiny library used to show wheels and sdists"
requires-python = ">=3.12"
dependencies = ["packaging>=24"]

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

Make the invisible visible: Build it and list what came out.

shell session · uv 0.12.5runs offline
$ uv build
Building source distribution...
Building wheel from source distribution...
Successfully built dist/demo_lib-0.1.0.tar.gz
Successfully built dist/demo_lib-0.1.0-py3-none-any.whl

$ python -m zipfile -l dist/*.whl
File Name                                             Modified             Size
demo_lib/__init__.py                           2020-02-02 00:00:00           47
demo_lib-0.1.0.dist-info/METADATA              2020-02-02 00:00:00          158
demo_lib-0.1.0.dist-info/WHEEL                 2020-02-02 00:00:00           87
demo_lib-0.1.0.dist-info/RECORD                2020-02-02 00:00:00          283

$ tar tzf sdist
demo_lib-0.1.0/uv.lock
demo_lib-0.1.0/src/demo_lib/__init__.py
demo_lib-0.1.0/pyproject.toml
demo_lib-0.1.0/PKG-INFO

What you see: Two artifacts: a wheel (py3-none-any.whl: pure Python, any platform) holding the code and a .dist-info folder with metadata, and an sdist (.tar.gz) holding the source, pyproject.toml and the lock file. The [build-system] block told uv to fetch hatchling, which did the work.

Why: The file is a contract: anyone with a frontend can build and install the project, with no setup.py to run by guesswork.

Land it I say pyproject.toml holds project metadata, the build-system table naming the backend, and tool settings, and that a frontend like pip or uv runs the backend to produce wheels and sdists.

Likely follow-ups
"What is the difference between dependencies and optional dependencies?"

dependencies are required: they are installed every time someone installs the package. [project.optional-dependencies] are named extras the user asks for, such as pip install pricer[postgres], which adds the database driver only for people who need it.

Think of it as "the package cannot work without this" against "this unlocks one feature". A library that supports three databases should not force all three drivers on every user, so each driver becomes an extra.

A third kind has appeared: [dependency-groups] (PEP 735). These are lists for development only, such as test, lint and docs. They are not written into the published package metadata, so users never see them. Recent versions of uv and pip read them; check that your tool version supports it.

My rule: runtime needs in dependencies, features in extras, tools for the team in dependency groups. That keeps what users download small and what developers need complete.

"How do I create a command-line tool?"

You add a [project.scripts] table that maps a command name to a function. Installing the package then creates the command for you.

pyproject.toml
[project.scripts]
pricer = "pricer.cli:main"

The text on the right means "import the module pricer.cli and call the function main". When pip or uv installs the package, it writes a tiny launcher file named pricer into the environment's bin folder. That launcher starts the right interpreter and calls the function. It also works on Windows, where the launcher is an .exe. This is called an entry point.

The function should take no arguments and read sys.argv itself, or use argparse or Typer. Return an integer and the launcher uses it as the exit code.

I test main as an ordinary function, and I also try uv run pricer once in CI to prove the launcher exists.

"Why not keep using setup.py?"

Because setup.py is a program, and the tools had to run it to learn anything about your package. That has three costs.

  1. Arbitrary code: to find the dependencies, pip executes the file. It could import something that is not installed yet, read the network or behave differently by machine. That is a security and reproducibility problem.
  2. Slow resolution: a resolver trying many versions had to build or run setup code for each candidate.
  3. Chicken and egg: setup.py needed setuptools to be installed before the tool could know it needed setuptools. [build-system].requires fixes that by stating it as data.

pyproject.toml is declarative, so any tool reads it without running anything. Legacy projects keep working because setuptools still supports setup.py, and I would not rush to rewrite a stable old package. For anything new, or anything I touch for another reason, I move to pyproject.toml only.

"How should I pin versions in dependencies?"

It depends on who consumes the file. A library uses ranges, an application uses exact versions from its lock file.

A library is installed next to many other packages. If it says requests==2.32.3 and another library needs requests>=2.33, the resolver cannot satisfy both, and the user's install fails. So a library states the loosest range that it has actually tested, such as packaging>=24. It adds an upper bound only when it knows a newer version breaks it.

An application is the final consumer, so nobody else's constraints matter. The lock file records the exact version and hash of every package, direct and indirect (Q128), and that is what gets installed and tested.

The trap is the middle ground: pinning exact versions in an internal library's metadata because "it is only internal". With 30 services (Q133) that becomes 30 resolver conflicts. Put exactness in the lock file, never in the library's metadata.

Q128 · Scenario. "A deploy broke because a transitive dependency upgraded itself. How do you prevent it?"

Reveal answer

Strong answer The cause is that the build resolved dependencies fresh on deploy. The project asked for requests>=2, and requests asked for other packages with ranges. A new minor release appeared on the package index overnight, so tomorrow's image contained different code from today's test run. Nobody changed the repository, and the program changed.

The prevention is a lock file: a generated file that records the exact version, and the file hashes, of every package including the indirect ones. The deploy installs from the lock file only, so the code in production is exactly what the tests ran against.

Practice: create it with uv lock (or pip-compile --generate-hashes, or Poetry's poetry.lock), commit it, install with uv sync --frozen in CI and in the image, which fails if the lock file is out of date instead of silently re-resolving. Update on purpose: a scheduled job or Dependabot opens a pull request that changes the lock file, runs the tests, and a human merges.

Hashes also protect against a package being replaced on the index with different content.

Picture it A lock file for a small library, and a frozen install.

The setup: The project's metadata says only packaging>=24. Without a lock file, any version from 24 up could be installed.

Make the invisible visible: The generated uv.lock (first lines) and the frozen sync.

uv.lock (excerpt) · uv 0.12.5runs offline
version = 1
revision = 3
requires-python = ">=3.12"

[[package]]
name = "demo-lib"
version = "0.1.0"
source = { editable = "." }
dependencies = [
    { name = "packaging" },
]

[package.metadata]
requires-dist = [{ name = "packaging", specifier = ">=24" }]

[[package]]
name = "packaging"
version = "26.4"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/c3/75/ffb1dc0ed12352139fb4ca0e3fde4325a23e3d0f3f40efe89717bc4f557b/packaging-26.4.tar.gz", ha
wheels = [
    { url = "https://files.pythonhosted.org/packages/ba/7b/5504f91c9c2733f693d7759e50ede5d27119d4da7e5836c46d3b5ff81d56/packaging-26.4-py3-none-any.wh
...
shell sessionruns offline
$ uv sync --frozen
 Installed 2 packages in 2ms
 + demo-lib==0.1.0 (from file:///.../demo_lib)
 + packaging==26.4

What you see: The range >=24 was resolved to exactly packaging 26.4, with a download URL and a SHA-256 hash for the wheel and the sdist. --frozen installs those versions without re-resolving. Earlier, I made two environments with packaging==24.0 and packaging==25.0: each printed its own version, proving that two versions never mix inside one environment.

Fresh resolve on deploy

Ranges decide the versions of the day.

ranges.txtruns offline
# requirements.txt
requests>=2
$ pip install -r requirements.txt

Install from the lock

Exact versions and hashes.

locked.txtruns offline
# uv.lock committed
$ uv sync --frozen

The shift: Test and deploy must install the same bytes.

Why: The lock file is the difference between "the version range I allow" and "the exact versions I ran". Deploys must use the second.

Land it I prevent surprise upgrades by committing a lock file with hashes, installing from it with a frozen sync in CI and in the image, and updating dependencies deliberately through reviewed pull requests.

Likely follow-ups
"What is the difference between uv lock and uv sync?"

They do two different jobs. uv lock decides which versions to use and writes them to uv.lock. uv sync installs those versions into the venv so it matches the file.

  1. uv lock: reads pyproject.toml, asks the index for what exists, resolves a consistent set and records versions and hashes. It changes the lock file. Nothing is installed.
  2. uv sync: reads the lock file and installs, upgrades or removes packages in the venv until it matches. By default it also re-locks first if the lock file looks out of date.
  3. --frozen: skip resolving altogether and use the file as it is, even if pyproject.toml has changed.
  4. --locked: check that the lock file is up to date with pyproject.toml, and fail if it is not.

In CI I prefer --locked: it catches a forgotten lock file. --frozen is for builds where I trust the file fully.

"Do libraries also need lock files?"

Yes, but for a different purpose. A library keeps a lock file so its own tests and CI are reproducible. It does not give that file to its users.

The reason is simple: users install the library with pip install or uv add, which read the published metadata and its ranges, never the lock file. The lock file stays in the repository and is not part of the wheel. Each application that uses the library has its own lock file and decides its own versions.

It helps the maintainers: without it, a test run next week may use a newer dependency and fail for a reason unrelated to the change under review.

A library should also test against the lowest versions its ranges allow, not just the locked ones (Q133), because that is what a user with older packages will get. So: lock file for repeatable CI, ranges for users, and a minimum-versions job to keep the ranges honest.

"How do I handle a security patch?"

I bump only that package, read the diff, test, and deploy. The command is uv lock --upgrade-package name, which re-resolves just that name and leaves the rest of the lock file alone.

The lock diff is small: one version and its hashes. I check that nothing else moved. If the fix needs a newer version of an indirect dependency, I upgrade that package by name too, the same way.

To make this routine, a bot such as Dependabot or Renovate opens the pull request daily, and a vulnerability scanner (for example pip-audit in CI) fails the build when a locked version has a known advisory. The aim is a patch that reaches production within a day without anyone having to remember. If the fix has no released version yet, I pin around the bad one and write down why.

"What if the index is down or a release is yanked?"

Then the build must not depend on the public index being up. I keep a copy of the packages close to the build.

A mirror or an internal index (Artifactory, Nexus, devpi, a registry in the cloud provider) stores every package the first time a build asks for it. Later builds read from the mirror, so an outage or a deleted project upstream does not stop deploys. A build cache that keeps downloaded wheels gives a lighter version of the same protection.

Yanked releases are gentler: they are hidden from new resolution, but an exact pin in a lock file can still install them. A deleted file is simply gone, which is why a mirror matters.

The hashes tie it together: whatever the mirror serves must match the hash in the lock file, so a mirror cannot quietly serve different content. If it does, the install fails loudly, and that is what I want.

Q129. "uv versus pip + pip-tools versus Poetry versus conda — when do you use each?"

Reveal answer

Strong answer They overlap but were built for different jobs.

Python packaging tools.
ToolPick it whenCost or catch
uvdefault for new work: fast resolver and installer, venv management, lock file, Python version management, project and script commands, written in Rustnewer than pip; some workflows (very unusual index setups) need checking
pip + pip-toolsyou want the simplest, most standard pieces: pip-compile writes a pinned requirements.txt with hashes, pip-sync installs ittwo tools and files to coordinate; slower; no project metadata management
Poetryan established team workflow with its own poetry.lock, publishing built inslower resolution, own metadata format historically (now supports PEP 621), plugin ecosystem
PDMstandards-first alternative to Poetry, built on the packaging standards (PEP 621)smaller community
conda / mambanative, non-Python dependencies matter: CUDA, GDAL, compiled scientific stacks, data science teamsseparate package ecosystem and environments; heavier; mixing with pip needs care

My default is uv: one tool for the interpreter, environment, lock file and install, and fast enough that CI time drops. I use conda when the hard part is native libraries a wheel cannot supply. I keep pip in mind because everything understands it, and any tool can export a plain requirements.txt for platforms that need one.

The stack rule: choose by who has to run it. A data scientist's GPU laptop is a conda case; a web service image is a uv case.

Picture it How little you type to go from nothing to a working locked environment with uv. Output from the course machine.

shell session · uv 0.12.5runs offline
$ uv --version
uv 0.12.5
$ uv build                      # builds wheel + sdist (Q127)
$ uv lock                       # writes uv.lock (Q128)
Resolved 2 packages in 2ms
$ uv sync --frozen              # installs exactly what uv.lock says
Installed 2 packages in 2ms

What you see: Resolving and installing a tiny project took milliseconds. On large dependency trees uv's advantage is its parallel downloads, a shared cache and a resolver written in Rust; I would time it on my own project rather than rely on a quoted multiple.

Why: A faster tool is not only convenience: if installing takes seconds, nobody skips the lock file or rebuilds environments out of fear.

Land it I default to uv for interpreter, environment, lock file and install, use conda when native scientific dependencies drive the choice, and keep plain pip and requirements.txt as the lowest common denominator.

Likely follow-ups
"Can I mix conda and pip?"

Yes, and it is common in data science teams, but the order and the rules matter.

  1. Conda first: create the environment and install everything conda can supply, especially packages with native code such as CUDA libraries, GDAL or numpy built against a particular math library.
  2. Pip second: install only what conda does not have, such as a small pure-Python package. Do it at the end, once.
  3. No replacing: do not let pip upgrade or replace a package conda installed. Conda cannot see that change, and a later conda install may undo it or leave a half-broken mix.

Write both lists in one environment.yml: the conda packages and a nested pip: section. Rebuild the environment from that file instead of editing it by hand.

If the environment ever gets strange, I delete it and rebuild. That is cheaper than diagnosing a mix of two package managers.

"What is a requirements.txt good for today?"

It is an export and compatibility format now, not the place where I decide dependencies. Almost every tool, platform and Dockerfile understands it, which is its real value.

A good one is flat, fully pinned and has hashes. Each line looks like requests==2.32.3 --hash=sha256:.... Installing it with pip install --require-hashes -r requirements.txt checks every download, and it works on a machine with nothing but pip.

The source of truth is the lock file (Q128) or pyproject.toml. With uv I generate the file with uv export, and with pip-tools pip-compile does the same job. I regenerate it whenever the lock changes and let CI check that the two agree.

Never edit it by hand. A hand-edited pinned file drifts away from the real requirements, and nobody can say why a version is there. Where a platform asks for it (some hosting services, older build systems), I generate it as a build artefact.

"How do I migrate from Poetry or pip-tools?"

I do it in small steps and compare the results before switching anything off.

  1. Metadata: a project using PEP 621 [project] works with uv directly. Older Poetry files with [tool.poetry] need their dependencies copied into [project]. A requirements.txt can be added with uv add -r requirements.txt.
  2. Lock: run uv lock. It resolves fresh versions, which may differ from the old lock.
  3. Compare: list old and new versions side by side. Any package that jumped a major version is a surprise to read about first.
  4. Switch: run the test suite on the new environment, update CI and the Dockerfile, and delete the old lock file in the same pull request.

If the old lock file is trusted, I can seed uv with its versions as constraints so that nothing moves during the migration. Then I upgrade on purpose afterwards.

"Does uv change which Python I run?"

Yes: uv can download, install and select Python versions itself, so you no longer need a separate version manager such as pyenv.

The commands are uv python install 3.14 to fetch an interpreter, uv python list to see what is available, and uv python pin 3.14 to write a .python-version file in the project. On the course machine, that is how 3.14, the free-threaded 3.14t and 3.15 release candidate sit next to the 3.12 that the system provides.

The version a project needs is also stated in requires-python in pyproject.toml. When you run uv sync, uv picks a matching interpreter, downloads it if it is missing, and builds the venv on top of it.

One practical benefit is that a new teammate or a CI runner needs only uv installed. The interpreter version is then part of the repository, not of the machine, which removes the "works with my Python" class of bugs.

Q130. "Wheel versus sdist — and why do some installs compile C code?"

Reveal answer

Strong answer A wheel (.whl) is a ready-to-install zip: files laid out exactly as they will be placed in site-packages, plus metadata. Installing it is just unzipping and copying, with no build step and no compiler. An sdist (.tar.gz) is the source plus pyproject.toml: to install it, the tool must first build it by running the build backend.

The wheel's file name says where it works: name-version-pythontag-abitag-platformtag.whl. py3-none-any means pure Python, any platform. cp312-cp312-manylinux_2_28_x86_64 means built for CPython 3.12 on 64-bit Linux with a glibc 2.28 or newer.

When you run pip install somepkg, the tool lists the available files and picks the best wheel from the tags your interpreter accepts. If no wheel matches (a brand-new Python version, an unusual platform like Alpine's musl, or the project never published one) it falls back to the sdist, and for a package with C or Rust code that means compiling on your machine: a compiler, headers and minutes of time, or an error.

This is why production builds use --only-binary :all: where possible, and why a Python upgrade can suddenly make an install slow or fail.

Picture it Look inside both artifacts and at which tags this interpreter accepts.

shell session · uv 0.12.5runs offline
$ python -m zipfile -l dist/*.whl
File Name                                             Modified             Size
demo_lib/__init__.py                           2020-02-02 00:00:00           47
demo_lib-0.1.0.dist-info/METADATA              2020-02-02 00:00:00          158
demo_lib-0.1.0.dist-info/WHEEL                 2020-02-02 00:00:00           87
demo_lib-0.1.0.dist-info/RECORD                2020-02-02 00:00:00          283

$ tar tzf sdist
demo_lib-0.1.0/uv.lock
demo_lib-0.1.0/src/demo_lib/__init__.py
demo_lib-0.1.0/pyproject.toml
demo_lib-0.1.0/PKG-INFO

What you see: The wheel holds the package folder and a dist-info folder, ready to be unpacked. The sdist holds the source and the build instructions. The file name of this wheel ends in py3-none-any, so it works anywhere.

Make the invisible visible: Which wheel tags does the course interpreter accept, best first?

wheel_tags.py output · Python 3.12runs offline
1068 tags this interpreter accepts, best first:
  cp312-cp312-linux_x86_64
  cp312-cp312-manylinux_2_39_x86_64
  cp312-cp312-manylinux_2_38_x86_64
  ...
  py30-none-any

What you see: This interpreter accepts 1,068 tags. The best tags are specific (cp312, this Python, Linux x86-64, with different glibc levels); the least specific is py30-none-any. An installer prefers the most specific wheel it finds.

Why: A wheel is a delivery, an sdist is a recipe. Compilation happens only when you are given the recipe.

Land it I describe a wheel as a pre-built, tag-labelled zip that is just unpacked, and an sdist as source that must be built, so installs compile when no matching wheel exists, and I avoid that in production with binary-only installs and a lock file.

Likely follow-ups
"What does manylinux mean?"

It is a family of platform tags (PEP 600) for Linux wheels that were built against an old glibc, so that one wheel runs on most distributions. glibc is the C library the program links to. A new glibc is backwards compatible, an old one is not, so building on an old one gives the widest reach.

The number is the minimum glibc. A wheel tagged manylinux_2_28 needs glibc 2.28 or newer, and pip checks that your system has it before choosing the wheel. Older names such as manylinux2014 are aliases for particular versions.

On the course machine the interpreter accepts these tags, newest first:

q130_tags.py outputruns offline
cp312-cp312-linux_x86_64
cp312-cp312-manylinux_2_39_x86_64
cp312-cp312-manylinux_2_38_x86_64

Alpine Linux uses musl, not glibc, so it needs musllinux wheels. Many projects do not publish those, which is why Alpine images often compile from source and why I use a Debian slim base instead.

"How do I publish wheels for a package with native code?"

You build one wheel for every platform and Python version you support, plus one sdist, and let CI do it.

For C and C++ extensions the standard tool is cibuildwheel. It runs in CI on Linux, macOS and Windows and builds inside manylinux containers, so the wheels carry the right tags. For Rust extensions maturin does the same job with Cargo. Both produce the files that you then upload to the index.

The count adds up: three operating systems, two processor types and four Python versions is already 24 wheels. With only the stable ABI (abi3), one wheel per platform covers every Python from a minimum version onward, at the price of skipping some version-specific C API.

Always publish the sdist as well. It is the fallback for platforms you did not build for, and some Linux distributions build from source on purpose. Test the wheels by installing them in a clean environment before releasing.

"Why is the free-threaded build relevant?"

Because free-threaded Python is a separate build with its own wheel tag, and a package that never published a wheel for it falls back to compiling.

On 3.14 the free-threaded interpreter is python3.14t and its wheels are tagged cp314t. A normal cp314 wheel is not accepted. The reason is that C extensions are written against the interpreter's internal data layout, and the free-threaded build changes it, so extensions must be rebuilt (and often adjusted) for it.

The effect when you try it is practical. A pure-Python package (py3-none-any) installs fine. A package with native code and no cp314t wheel starts a compile, which needs a compiler and headers and may fail (Q79).

So before moving a service to the free-threaded build, I list its native dependencies and check that each publishes cp314t wheels.

"How do I check what will be installed without installing?"

With a dry run, and for compile risks with a binary-only download. Both are checks, so nothing is changed in the environment.

  1. Dry run: pip install --dry-run -r requirements.txt, or uv pip install --dry-run, resolves everything and prints which package and which file it would pick.
  2. Binary only: pip download --only-binary :all: -r requirements.txt -d /tmp/wheels downloads wheels and fails immediately if some package has only an sdist. That error names the package that would have compiled.
  3. Look at the name: in the output, a file ending .tar.gz is an sdist and means a build step.

I run the second command in CI on the production platform, for example inside the same base image as the deploy. It turns "the deploy took twelve minutes and failed on a missing compiler" into a red check on the pull request, which is where I want to find it, and the same check after each Python upgrade shows which packages have no wheel yet.

Q131 · Scenario. "Two services on one host need different versions of the same library. What are your options?"

Reveal answer

Strong answer The root problem: one Python process has one sys.modules, so it can load only one version of a package at a time. Two services in separate processes have no such problem, as long as each has its own environment.

Options, from best to worst. 1. One virtual environment per service: each service has its own .venv (or its own container image) with its own lock file. This is the normal answer and costs only disk space. 2. Containers: stronger isolation, including the system libraries, and the same unit as production.

3. Align versions: upgrade the lagging service so that both can use one version: reduces long-term cost. 4. In one process (rarely worth it): split into two processes that talk over a pipe or HTTP, or vendor one copy of the library under a different name. Avoid import tricks.

I choose option 1 for tools on a shared host, option 2 for anything deployed, and I schedule option 3 so the differences do not grow.

Picture it Two environments on one machine, each with its own version of the same package.

The setup: uv venv twice, then install packaging==24.0 into one and packaging==25.0 into the other.

shell session · uv 0.12.5, Python 3.14runs offline
uv venv --python 3.14 svcA && uv pip install --python svcA/bin/python "packaging==24.0"
uv venv --python 3.14 svcB && uv pip install --python svcB/bin/python "packaging==25.0"
svcA/bin/python -c "import packaging; print(packaging.__version__)"
svcB/bin/python -c "import packaging; print(packaging.__version__)"
outputruns offline
service A: venv svcA -> packaging 24.0
service B: venv svcB -> packaging 25.0

What you see: Each service sees its own version. Both live on the same machine at the same time, because each interpreter searches its own site-packages only.

Java · classloaders

Different versions of a jar need separate class loaders or an application server's module system.

shellruns offline
// one classpath per application
java -cp app-a.jar:guava-31.jar A
java -cp app-b.jar:guava-33.jar B

Python · environments

One folder per application, one interpreter process each.

shellruns offline
svcA/.venv  ->  packaging 24.0
svcB/.venv  ->  packaging 25.0
# each service: its own lock file

The shift: Both ecosystems solve it by giving each application its own search path; Python does it with a folder, Java with a classpath.

Why: There is no "two versions in one process" in normal Python: isolation comes from processes and folders, not from the import system.

Land it I give each service its own environment or container image with its own lock file, because a process can load only one version of a package, and I plan to bring versions together over time.

Likely follow-ups
"What if both libraries must run in the same process?"

Then they need versions that work together, because one process has one sys.modules and can hold only one copy of a package under one name. There is no clean way around that, only choices.

  1. Find a common version: usually the older library's requirement is a range, not a real limit. I try the newer version with its tests first.
  2. Upgrade the lagging one: if library B needs an old release of A, I update B or open a pull request against it.
  3. Split the process: move one of the two behind a small HTTP or queue boundary, so each side has its own environment.

Tricks exist, such as loading one copy under a second name. I avoid them. Tools, type checkers and pickled data all assume one name per module, so failures are confusing and show up late.

Splitting a process costs a network call and a deployment. That is still cheaper than debugging two half-loaded versions.

"Do containers replace virtual environments?"

For deployment they do the isolating, and for most services one image holds one environment. That does not make a venv useless inside the image.

The reasons I keep one are practical. The path is fixed, for example /app/.venv, so the PATH and the start command are the same everywhere. A multi-stage build can copy exactly that folder from the builder stage into a slim final stage, without compilers. And the application's packages stay apart from whatever the base image installed for its own scripts.

Containers also isolate things a venv cannot: system libraries, the operating system, environment variables and the file system. If service A needs OpenSSL 1.1 and service B needs 3.0, two venvs do not help but two images do.

On a shared development host, I would still use a venv per project, because starting a container for every script is heavy. So: a venv for working, an image for shipping, and the lock file feeding both.

"How do I keep many environments consistent?"

The honest answer is that consistency across many environments is a process problem, not a tool problem. Drift is the real cost, so I make it visible and cheap to fix.

  1. Shared inputs: a common constraints file, or a base lock file for the libraries every service uses (web framework, Pydantic, the HTTP client), so teams start from the same versions.
  2. Automatic updates: a bot (Renovate or Dependabot) opens upgrade pull requests in every repository, so no service silently falls two years behind.
  3. Measurement: a script reads each repository's lock file and counts how many versions of each major library are live. If FastAPI shows up in five different versions across 30 services, that is the number I report.

I also keep the Python version the same everywhere where possible, since interpreters differ more than libraries do. The target is not identical environments but a small, known spread that shrinks over time.

"What about a shared site-packages for disk space?"

They share the files on disk, but not the import path, which gives the space saving without the coupling.

uv keeps a global cache of unpacked packages. When you create or sync a venv, it uses hard links (or copy-on-write copies on some file systems) from the cache into site-packages. A hard link is a second name for the same bytes on disk, so ten venvs that use the same version of numpy store that version once.

Each venv still has its own folder and its own pyvenv.cfg, so imports in one environment never see the other's packages. Removing one venv removes only its links.

A real shared site-packages would bring back the original problem: one upgrade changes every service at once. Disk is cheap and a version clash is not, so I never share the import path. Hard links need the cache and the venv on one file system; otherwise uv copies.

Q132. "How do you lay out a Python project (the src layout), and why?"

Reveal answer

Strong answer The src layout puts the importable package inside a src/ folder, next to tests/ and pyproject.toml. The alternative, the flat layout, puts the package directly in the project root.

project treeruns offline
# illustrative
pricer/                     # repository root
  pyproject.toml
  uv.lock
  README.md
  src/
    pricer/                 # the importable package
      __init__.py
      money.py
      service.py
  tests/
    test_money.py
    conftest.py

The reason is a trap in the flat layout: when you run python or pytest from the project root, the current directory is on the import path, so import pricer finds the source folder itself, not an installed copy. Your tests pass even when the packaging is broken: a file missing from the wheel, a wrong package name, a data file not included. You find out when a user installs it.

With the src layout, import pricer from the root fails unless the package is installed, so you must install it (an editable install, uv sync does that). Tests then run against what users will get, and packaging mistakes show up in CI.

Picture it The trap, run for real in two tiny projects with no installation.

shell session · Python 3.14runs offline
$ cd flat && python -c "import shop"   # nothing installed
imported shop from: ./shop/__init__.py
$ cd src_layout && python -c "import shop"   # nothing installed
ModuleNotFoundError: No module named 'shop'

What you see: In the flat layout, import shop worked at once, because Python found the local folder: packaging could be completely broken and nobody would notice. In the src layout, the import failed with ModuleNotFoundError until the package is installed, which is the signal we want.

Flat layout

Imports work by accident.

flatruns offline
shop/
  shop/__init__.py
  tests/
# python -c "import shop"  -> works
# even though nothing is installed

src layout

Imports require an installed package.

srcruns offline
shop/
  src/shop/__init__.py
  tests/
# python -c "import shop"  -> fails
# until: uv sync (editable)

The shift: The src layout makes the tests use the installed package, so packaging bugs fail in CI, not for your users.

Why: Python puts the current directory first on the import path. The src layout takes your code out of that path on purpose.

Land it I use the src layout so the project root is not importable, which forces tests to run against an installed package and exposes packaging mistakes early.

Likely follow-ups
"Is there a downside?"

Yes, a small one: the project must be installed before anything can import it. That means a few extra steps for people who are new to it.

With the src layout, running python or pytest from the root does not find pricer until it is installed in the environment. If you forget, you see ModuleNotFoundError. In practice the tools hide this: uv sync installs the project in editable mode, and uv run pytest syncs first. Newcomers still find the extra folder strange, and some editors need to be told that src is a source root so that they can resolve imports.

There is also the extra directory level in every path. I accept these costs because the failure they prevent is a package that passes tests but is broken when installed.

For a throwaway script, or a notebook project that is never installed, I would not bother with the src layout. The benefit comes from packaging, so it matters when you ship a package.

"Do applications need it too?"

If the application is packaged, yes, for the same reason. If it is just a folder of scripts, no.

Take a service whose Docker image is built by installing a wheel. With a flat layout, the tests run against the folder in the repository, while production runs the installed wheel. If the wheel misses a file, such as a SQL template or a JSON schema, the tests pass and the container crashes on the first request. With the src layout, the tests import the installed copy and show the missing file in CI.

That is the whole argument: the thing you test should be the thing you deploy.

Where I relax the rule is a collection of operational scripts, or a small internal tool that is run straight from a checkout and never packaged. There the flat layout is simpler, and nothing is gained from separate installs.

My test is one question: will this be installed somewhere other than my checkout? If yes, use src/.

"Where do tests and data files go?"

Tests go in a top-level tests/ folder outside the package. Data files go inside the package, and the package finds them through importlib.resources.

Tests stay outside because they should not be shipped to users, and putting them beside src/ keeps the wheel small. They import the package like any user would, which is the point of the layout.

Data files need two things. First, they sit inside the package folder, for example src/pricer/data/rates.json. Second, the build configuration includes them: hatchling includes files in the package by default, while with setuptools you set package-data or include-package-data. Then you read them with importlib.resources.files("pricer") / "data" / "rates.json".

The common mistake is open("data/rates.json"). That path is relative to the working directory, so it works from the project root and fails anywhere else. importlib.resources also works when the package is installed from a zip. I check this by installing the wheel in a clean environment during CI.

"How does it relate to editable installs?"

An editable install gives you the src layout's honesty and the quick edit-and-run cycle together. It puts a small pointer into the environment instead of copying your code.

When you run uv sync or pip install -e ., the environment gets a .pth file or an import hook that points at your src/ folder. import pricer then loads the files in your checkout, and an edit takes effect the next time Python starts, with no reinstall.

The flat layout instead puts the whole project root on the path, so test folders and stray files are importable too. With src/, only the package is exposed, so an import that works in development also works for users.

One caveat: an editable install tests your source folder, not the built wheel. Packaging problems such as missing data files can still hide. So CI should also build the wheel and install it in a clean environment for one smoke test, as the release pipeline in Q133 does.

Q133 · Design. "Design the build-and-release pipeline for an internal library used by 30 services."

Reveal answer

Strong answer The goals: a release is repeatable, safe for 30 consumers, and cheap enough that people do it often.

  1. Versioning: semantic versioning with the version taken from a git tag (hatch-vcs or a release bot), so the tag is the single source of truth. A major version means a breaking change.
  2. CI on every pull request: format and lint (Ruff), type check (mypy or pyright), tests on the supported Python versions (3.12, 3.13, 3.14) in a matrix, and a build of the wheel and sdist to check the packaging, including installing the wheel in a clean environment and running a smoke test.
  3. Release on tag: CI builds with uv build, publishes to the internal index (Artifactory, a GitLab or GitHub package registry, devpi) using short-lived credentials, not a stored password. Attach a changelog generated from commit messages.
  4. Protect consumers: a deprecation policy (warn for one minor release before removal), a compatibility test job that runs the test suites of the three biggest consumers against the release candidate, and the ability to yank a bad release.
  5. Roll out: consumers pin through their lock files; a bot opens upgrade pull requests in all 30 repositories, so adoption is visible and reviewable.
  6. Support window: support the current and previous major; document it.

I would measure the pipeline: time from merge to published (target under 10 minutes), and how many consumers are within one minor version of latest.

Picture it The release job as a configuration sketch. This is an illustration of the design; I did not run it against a real index.

release.yml (illustrative)runs offline
# illustrative
on:
  push:
    tags: ["v*"]
jobs:
  test:
    strategy:
      matrix: {python: ["3.12", "3.13", "3.14"]}
    steps:
      - uses: astral-sh/setup-uv@v5
      - run: uv sync --frozen --python ${{ matrix.python }}
      - run: uv run ruff check . && uv run mypy src && uv run pytest -q
  publish:
    needs: test
    permissions: {id-token: write}      # short-lived credentials
    steps:
      - run: uv build
      - run: uv run --with twine twine check dist/*
      - run: uv publish --publish-url $INTERNAL_INDEX

Make the invisible visible: What the build step really produces, shown earlier for a tiny library.

shell session · uv 0.12.5runs offline
$ uv build
Building source distribution...
Building wheel from source distribution...
Successfully built dist/demo_lib-0.1.0.tar.gz
Successfully built dist/demo_lib-0.1.0-py3-none-any.whl

Why: The pipeline treats the artifacts, the wheel and the sdist, as the product. Tests that run on the installed wheel catch packaging bugs before any consumer sees them.

Land it I make the git tag the single source of the version, run lint, types and a Python-version matrix on every pull request, publish wheels and an sdist from CI with short-lived credentials, and protect consumers with deprecation warnings and a canary run of their tests.

Likely follow-ups
"How do you stop a breaking change reaching 30 services at once?"

Mostly by not letting it reach them all at once. Three mechanisms work together, and none needs 30 teams to move on one day.

  1. Lock files: every service pins its own version, so publishing 3.0.0 changes nothing in production until a service chooses to upgrade.
  2. Canary test job: before releasing, CI runs the test suites of the three biggest consumers against the release candidate. If their tests fail, I know before anyone installs it.
  3. Staged upgrades: a bot opens upgrade pull requests, starting with the friendliest teams and the least critical services. Problems found there are fixed before the critical services upgrade.

A major version number is the signal for a break, and the deprecation policy gives a warning period before it: for one minor release the old call still works and raises a DeprecationWarning naming the replacement. Consumers can run their tests with warnings as errors to find the uses early.

Without that notice, a breaking change is a surprise for 30 teams.

"How do you handle a bad release?"

I yank it, publish a fixed patch release quickly, and write it in the changelog. I do not delete it.

Yanking (PEP 592) hides a release from the resolvers, so new installs and new lock runs do not choose it. A service that already pinned it exactly can still install it, which means yanking cannot break anyone's build. Deleting a file does the opposite: every lock file that points at it fails to install, and the failure appears in the middle of someone else's deploy.

The sequence I use:

bad release steps
1. yank 2.4.0 on the index, with a reason
2. fix on main, tag 2.4.1, CI publishes it
3. changelog: "2.4.0 yanked: wrong rounding in price_in()"
4. bot opens pull requests moving locks to 2.4.1

Step 4 is what repairs the services that already took the bad version. I also add a regression test for the bug and ask what check in the pipeline should have caught it.

"What does the library test against?"

It tests against the edges of what it promises, not only the middle. Consumers will combine my library with their own versions of everything else, so I cover both ends.

First, the Python versions: the oldest and the newest I claim to support, such as 3.12 and 3.14, and the ones in between in a CI matrix. Second, the dependency versions: a normal job with the locked versions, and a "lowest" job that installs the minimum version of every dependency my ranges allow. With uv this is uv pip compile --resolution lowest, or the --resolution lowest-direct flag for direct dependencies only.

The lowest job finds a classic bug: I wrote packaging>=20 but used a function added in 22. With only the latest versions in CI, nobody notices until a consumer with an older package reports it.

A smoke test of the built wheel in a clean environment finishes it: install, import, call one function. The cost is more CI minutes, which is cheaper than 30 consumers finding the problem.

"Who owns the pipeline?"

The library team owns it, and it should be a template rather than a heap of per-library scripts.

The people who understand what a release means are the maintainers, so they run it and carry the on-call for a bad release. If a separate team owned the pipeline, a broken release would wait in a queue.

What a platform team can do is provide the reusable part: a shared workflow, for example a reusable GitHub Actions workflow or a GitLab template, that does lint, type check, test matrix, build, smoke test and publish. A library then declares only its name, its Python versions and its index. When the platform team improves the workflow, every library gets it by updating one version number.

Ownership also covers the human side: someone names the support window, decides when a deprecation ends, and answers consumers' questions.

I would measure the result by the number of libraries on the template and by the median time from merge to published, which should be under ten minutes.

Drill · Testing

Fixtures, patching the right name, independent tests, async tests, and property-based testing for money-like code.

Q134. "pytest fixtures: scopes, yield teardown and conftest.py."

Reveal answer

Strong answer A fixture is a function that prepares something a test needs (a database connection, a temporary directory, a fake client). A test asks for it by naming it as a parameter, and pytest runs the fixture and passes in the result. That is dependency injection by name.

Scope decides how long the result lives: function (default: new for every test), class, module, package, or session (once for the whole run). Use a wider scope for expensive things (an engine, a container) and keep per-test state at function scope so tests stay independent.

A fixture with yield runs everything before the yield as set-up and everything after as teardown, even if the test failed. This replaces try/finally. Fixtures can use other fixtures, and pytest builds the order: wider scopes first, torn down last.

conftest.py is a special file: fixtures defined there are available to every test in that folder and below, with no import.

Picture it Two tests sharing a session-scoped engine and a function-scoped connection.

conftest.py and test_fixtures.py · pytest 9.1.1runs offline
import pytest

@pytest.fixture(scope="session")
def engine():
    print("\n  [setup session engine]")
    yield "engine"
    print("\n  [teardown session engine]")

@pytest.fixture
def conn(engine):
    print("\n  [setup conn]")
    yield f"conn-on-{engine}"
    print("\n  [teardown conn]")

# test_fixtures.py
def test_one(conn):
    assert conn.startswith("conn")

def test_two(conn):
    assert "engine" in conn

Make the invisible visible: Run with -s to see the prints in order.

pytest test_fixtures.py -s -v · Python 3.12runs offline
collecting ... collected 2 items

test_fixtures.py::test_one 
  [setup session engine]

  [setup conn]
PASSED
  [teardown conn]

test_fixtures.py::test_two 
  [setup conn]
PASSED
  [teardown conn]

What you see: The session engine was set up once before the first test and torn down once at the very end. The connection was set up and torn down around each test. Teardown lines ran in reverse order of set-up, and the inner fixture (connection) finished before the outer one (engine).

Why: Scope is a trade between speed and isolation: a wider scope saves set-up time, and a narrower scope guarantees a clean state.

Land it I explain fixtures as named, injected set-up with scopes for lifetime and yield for guaranteed teardown, shared through conftest.py, and I keep mutable state at function scope.

Likely follow-ups
"What is autouse?"

It is a fixture that runs for every test in its scope without any test asking for it. You mark it with @pytest.fixture(autouse=True).

Normally a test names a fixture as a parameter, and that is how a reader sees what it needs. With autouse, nothing in the test signature shows the fixture, so it is hidden set-up. I use it only for things that must be true for every test and that no test should have to remember: resetting a global cache, freezing the clock, blocking real network calls, or setting an environment variable.

conftest.py
@pytest.fixture(autouse=True)
def no_network(monkeypatch):
    def refuse(*a, **k):
        raise RuntimeError("real network call in a test")
    monkeypatch.setattr("socket.socket.connect", refuse)

That example is a good use: a safety net with no effect on results. If an autouse fixture creates data that tests then rely on, it is too clever, and I make it an explicit fixture instead.

"How do I parametrise a fixture?"

You pass params to the fixture decorator, and pytest runs every test that uses the fixture once for each value. The current value is in request.param.

It looks like this: @pytest.fixture(params=["sqlite", "postgres"]) followed by def db(request): which builds the right backend from request.param. A test that takes db as an argument then appears twice in the results, as test_save[sqlite] and test_save[postgres].

This differs from @pytest.mark.parametrize in where the variation lives. Parametrize varies the inputs of one test. A parametrised fixture varies the environment for every test that uses it, so you write the tests once and run them against several backends, configurations or fake and real clients. The same trick checks that a fake and the real implementation obey one contract (Q137).

A warning: the number of runs multiplies. Ten tests and four params is 40 runs, so I keep the list short and use ids to make failures readable.

"Fixture or plain helper function?"

I use the simplest tool that does the job. A plain helper is simpler, and a fixture is for things that need pytest's help.

  1. Plain function: when it only builds a value, for example make_order(total=10). You call it where you need it, see its arguments, and get one fresh object each time. It needs no framework, and your editor can jump to it.
  2. Fixture: when it needs teardown after the test, uses other fixtures such as tmp_path or monkeypatch, or is shared by many test files through conftest.py.
  3. Both: a fixture that returns a factory function, when tests need several objects with different arguments but also need clean-up.

The trap is making everything a fixture. Then a reader has to hunt through conftest.py files to learn what a test uses, and the arrangement lives away from the assertions. A short, visible helper in the same file is easier to read. I add a fixture when I see the same set-up and teardown repeated three times.

"What goes wrong with wide scopes?"

State leaks. A wide-scope fixture is created once and then shared, so any test that changes it affects every test after it.

Imagine a session-scoped fixture that returns a list of products, and one test appends a product. Later tests now see an extra product, and the results depend on the order in which tests run. The tests pass when run alone and fail together, the pattern in Q139. With pytest-randomly or a parallel run the order changes, and the failure looks random.

My rules: use a wide scope only for expensive, read-only or resettable resources, such as a database engine, a container, or a compiled regular expression. Hand each test its own clean state from a function-scoped fixture on top, for example a transaction that is rolled back at the end of the test, or a freshly truncated table.

The speed gain from a wide scope is real, but correctness comes first.

Q135 · Scenario. "patch("module.func") has no effect in your test. Why?"

Reveal answer

Strong answer Because you patched the wrong name. patch replaces an attribute on a module object. If another module did from rates import fetch, it copied the function into its own namespace when it was imported. Replacing rates.fetch later changes the original module's name, but the other module still has its own name pointing at the real function.

The rule: patch where the name is looked up, not where it is defined. If service.py uses fetch through from pricer.rates import fetch, patch pricer.service.fetch. If it uses import pricer.rates and calls pricer.rates.fetch(), patching pricer.rates.fetch works.

A cleaner fix is to avoid patching: pass the dependency in as a parameter (price_in(currency, amount, fetch=fetch)), or hold it in an object that tests can replace with a fake (Q137).

Picture it Two tests, same mock, different targets.

pricer/service.py and test_patch.pyruns offline
from pricer.rates import fetch          # name copied into service's namespace

def price_in(currency, amount):
    return amount * fetch(currency)

# test_patch.py
from unittest.mock import patch
from pricer.service import price_in

def test_wrong_target():
    with patch("pricer.rates.fetch", return_value=2):
        assert price_in("EUR", 10) == 20

def test_right_target():
    with patch("pricer.service.fetch", return_value=2):
        assert price_in("EUR", 10) == 20

Make the invisible visible: Run them.

pytest test_patch.py -q · Python 3.12 (excerpt)runs offline
F.                                                                       [100%]

=================================== FAILURES ===================================
...

What you see: test_wrong_target failed with RuntimeError: real network call: the patch had no effect, and the real fetch ran. test_right_target passed.

two names, one functionruns offline
# illustrative
pricer.rates   : fetch -----> <real function>
pricer.service : fetch -----> <real function>   (copied at import)

patch("pricer.rates.fetch")   : rates.fetch -> mock ; service.fetch still real  (x)
patch("pricer.service.fetch") : service.fetch -> mock                         (ok)

Patch where it is defined

The copy in service is untouched.

wrong.pyruns offline
patch("pricer.rates.fetch")
# service.fetch is still real

Patch where it is looked up

The name the code reads is replaced.

right.pyruns offline
patch("pricer.service.fetch")
# service calls the mock

The shift: Replace the name the code under test actually reads.

Why: from x import y makes a second name. Mocks must replace the name that the code under test actually reads.

Land it I patch where the name is used, not where it is defined, and I prefer passing dependencies in so I do not need to patch at all.

Likely follow-ups
"How does monkeypatch differ from unittest.mock.patch?"

Both undo their change afterwards, so the real difference is the extras. monkeypatch.setattr is simple replacement, and patch builds a mock object.

monkeypatch is a pytest fixture. It sets an attribute, an environment variable (setenv), a dictionary item or the working directory, and reverts it at the end of the test. You give it the replacement you want, a plain function or value, and nothing else is added.

unittest.mock.patch replaces the target with a MagicMock by default, which records calls. You can then assert mock.assert_called_once_with(...), set return_value or side_effect (to raise an error, or return different values per call), and use autospec=True to copy the real signature.

My rule: if I only want different behaviour, I use monkeypatch. If I want to check how the code called the dependency, or to simulate a failure on the second call, I use patch. Both follow the same where-to-patch rule.

"What if the code is imported inside a function?"

Then the name is looked up at the moment the function runs, so patching the module that owns the function works. That is the same rule as before: patch where the name is looked up.

Take a function that contains from pricer.rates import fetch on its first line. Every call executes that import, which looks up fetch in pricer.rates at that moment and copies it into a local name. If your test patched pricer.rates.fetch before the call, the import finds the fake. Patching pricer.service.fetch would fail with AttributeError, because that name does not exist in the service module.

A module-level from rates import fetch shows the opposite case, where the copy is made once at import:

q135_patch.py outputruns offline
patched where defined : real
patched where used    : fake

I read the code and ask which dictionary is searched for this name when the line runs. I patch that one.

Function-level imports are used to avoid import cycles or slow start-up. They can make patching confusing, so passing the dependency as an argument is easier to test.

"How do I make a mock respect the real interface?"

By using autospec. An ordinary mock accepts any call, so tests can pass while the real code would fail.

A plain MagicMock has every method you ask for. If you write client.fetch_rate("USD") but the real method is named get_rate, the mock answers anyway and the test passes. The same holds for wrong argument counts. The bug shows up in production.

create_autospec(RatesClient), or patch("pricer.service.RatesClient", autospec=True), builds the mock from the real object. It copies the names and the signatures. A misspelt method raises AttributeError, and a call with the wrong arguments raises TypeError, exactly like the real thing.

Autospec has a cost: it must inspect the real object, so it is a little slower, and it follows the real class when that class changes. I count that as a benefit, since a rename in the real class now breaks the tests that use it. I also use spec_set where I want writing to unknown attributes to fail (Q137).

"Why is heavy patching a smell?"

Because it ties the tests to how the code is wired internally. A refactor that keeps the behaviour then breaks tests, and people stop trusting them.

Say the service moves from from pricer.rates import fetch to using a client object. Every test that patched pricer.service.fetch breaks, though the prices are the same. The tests were testing the import structure, not the result.

It is usually a design signal. The code creates its own dependencies inside functions, so the only way to replace them is to reach in from outside.

The cure is to pass dependencies in, as arguments or constructor parameters (price_in(currency, amount, fetch=fetch)). Then the test hands in a small fake and needs no patch at all. The code is also easier to read, because its inputs are visible in the signature.

I still allow patches at the edges, such as the clock.

Q136. "parametrize, marks, and keeping a 4,000-test suite fast."

Reveal answer

Strong answer @pytest.mark.parametrize runs one test function with many input sets, and reports each as its own test with its own name. It replaces copy-pasted tests and loops inside a test (where the first failure hides the rest). Give cases readable ids so a failure says test_total[three], not test_total[2-2.50-7.50].

Marks are labels: @pytest.mark.slow lets you run pytest -m "not slow" locally and everything in CI. Register them in pytest.ini so typos are caught.

Keeping 4,000 tests fast: measure first with --durations=20; the slowest 20 usually dominate. Then avoid real sleeping and real network, use an in-memory or per-worker database, use wide-scope fixtures for expensive set-up, run in parallel with pytest-xdist (-n auto), run only affected tests on a pull request and everything on merge, and split a fast layer (seconds) from a slow integration layer.

Parallel runs need independent tests: shared files, ports and database rows must be unique per worker.

Picture it Parametrised cases with ids, a slow mark, and then parallel execution.

test_param.py · pytest 9.1.1runs offline
import pytest
from decimal import Decimal

@pytest.mark.parametrize("qty,price,total", [
    (1, "2.50", "2.50"),
    (3, "2.50", "7.50"),
    (0, "9.99", "0.00"),
], ids=["one", "three", "zero"])
def test_total(qty, price, total):
    assert Decimal(price) * qty == Decimal(total)

@pytest.mark.slow
def test_big():
    assert sum(range(10**6)) > 0

Make the invisible visible: Run only the fast ones.

pytest test_param.py -v -m "not slow" · Python 3.12runs offline
collecting ... collected 4 items / 1 deselected / 3 selected

test_param.py::test_total[one] PASSED                                    [ 33%]
test_param.py::test_total[three] PASSED                                  [ 66%]
test_param.py::test_total[zero] PASSED                                   [100%]

What you see: Three cases ran as three named tests, and the slow one was deselected.

Make the invisible visible: Parallel run of 600 tests that each wait 20 ms (a stand-in for I/O), serial and with 8 workers.

pytest with and without pytest-xdistruns offline
$ pytest bench -q
600 passed in 13.91s
$ pytest bench -q -n 8
600 passed in 9.26s
# measured on the course machine (12 cores); your numbers will differ

What you see: Serial took 13.9 s (600 x 20 ms plus overhead). With eight workers it took 9.3 s, only 1.5x faster. Each worker is a new process that must start Python and load the plugins of this large environment; that fixed cost (likely about 7 s here, I did not time it separately) dominates a small suite. For a 4,000-test suite the fixed cost is spread thin and the gain grows, but this shows why I measure before assuming that "parallel" means "fast".

Why: Speed comes from removing waiting and from parallelism that pays for its start-up. Both need numbers.

Land it I parametrise with readable ids, use marks to split fast and slow tests, find the slow ones with --durations, remove real waiting, and add xdist when the suite is big enough to repay worker start-up.

Likely follow-ups
"Parametrize or a loop inside the test?"

Parametrize, almost always. A loop inside the test hides information, and parametrize gives you one result per case.

With a loop, the test stops at the first failing case, so if cases two and five are both wrong you learn about two only. The report says that one test failed, and you must dig for which input caused it. With @pytest.mark.parametrize, every case is its own test. Each runs even if another failed, appears by name in the report, and can be run alone by id, for example pytest -k three or pytest "test_total.py::test_total[three]".

There is one case for a loop, and that is when the loop is the thing under test: for example checking an invariant on every item of one result.

Rule of thumb: many inputs, one behaviour is parametrize. One scenario with many steps is one test.

"How do I keep test data readable?"

I put input and expected result on the same line, give cases names, and keep the table close to the test.

  1. Named cases: pytest.param(0, "0.00", id="zero quantity") makes the report say test_total[zero quantity]. A failure then reads like a sentence.
  2. Small factories: when a case needs an object, a helper such as make_order(total=10) hides the ten fields that do not matter, so what remains is what the case is about.
  3. One table, in one place: a large table sits at the top of the file as a list, or in a data file for really big sets.

The goal is that someone who has not seen the code can read a row and say what the rule is.

I avoid computing the expected value with the same formula as the code under test. That repeats the bug in the test, so expectations are literal numbers.

"What makes tests slow in real suites?"

In my experience five causes cover most of the slow suites, and they are easy to confuse with "Python is slow".

  1. Database set-up per test: creating the schema for each test, when one schema and a rollback per test would do. 4,000 tests at 50 ms is 200 seconds from this alone.
  2. Real network: HTTP calls to a sandbox or DNS lookups that time out.
  3. Real waiting: time.sleep or retry back-off that waits for real seconds.
  4. Heavy imports: loading a large library in many modules, or an application that builds all its objects at import.
  5. Expensive function-scoped fixtures that could be shared safely.

I do not guess. I run pytest --durations=20 and look at the slowest tests and the slowest set-ups, then profile one of them with cProfile if the cause is not obvious. Usually a handful of tests account for a large share of the time, and fixing those pays for the effort.

"How should CI use all this?"

CI should give fast feedback on a pull request and full confidence on merge, and it should use two different test selections to get both.

On a pull request, run the fast layer: unit tests and the cheap integration tests, in parallel with pytest -n auto. If the tooling can find affected tests, run only those. Feedback that arrives after an hour is ignored.

On merge to main and nightly, run everything: slow tests, the real-database tests (Q137), the minimum-version job and the other Python versions.

The trap is a "fast" selection that is allowed to drift until it misses bugs. I watch two numbers: the time of the PR job, which I keep under a target such as ten minutes, and how often a bug is first caught by the nightly job. If the second number is high, the fast selection is leaving gaps.

Q137. "Mocks, fakes or real dependencies (Testcontainers) — when each?"

Reveal answer

Strong answer They answer different questions, and good suites use all three in different places.

Test doubles and real dependencies.
ChoicePick it whenCost or catch
Mock (Mock, patch)check an interaction: "was send called once with these arguments?"; simulate an error that is hard to produceties the test to how the code works, not what it achieves; a plain Mock accepts any method name, even misspelt ones
Fake (a small working implementation)the dependency is simple and used by many tests: an in-memory repository, a fake clock, a fake rates clientyou must keep the fake faithful to the real thing; test it against the same contract
Real dependency (Testcontainers)behaviour depends on the real system: SQL semantics, transactions, locking, migrationsslower (seconds to start), needs Docker in CI; run fewer such tests, more selectively

My default is fakes for logic, a few real-database tests for the data layer, and mocks sparingly for interaction checks and for failures. Mock-heavy suites pass while production fails, because the mocks encode the author's assumptions about the dependency.

When I do use a mock, I use create_autospec, so the mock has the real signature and a typo fails.

Picture it The same function tested with a fake, a plain mock and an autospecced mock.

fake_vs_mock.py · Python 3.12 (venv)runs offline
from unittest.mock import Mock

class RateClient:                       # real thing: network
    def rate(self, cur): raise RuntimeError("network")

class FakeRates:                        # a small working fake
    def __init__(self, table): self.table = table
    def rate(self, cur): return self.table[cur]

def price(client, cur, amount): return amount * client.rate(cur)

fake = FakeRates({"EUR": 2})
print("fake :", price(fake, "EUR", 10))

mock = Mock(); mock.rate.return_value = 2
print("mock :", price(mock, "EUR", 10), "| calls:", mock.rate.call_args_list)
mock.rate_typo.return_value = 99        # a typo'd method is silently accepted
print("mock accepts any name:", mock.rate_typo("EUR"))
from unittest.mock import create_autospec
strict = create_autospec(RateClient, instance=True); strict.rate.return_value = 2
try:
    strict.rate_typo("EUR")
except AttributeError as e:
    print("autospec rejects it:", e)

Make the invisible visible: Run it.

output · Python 3.12runs offline
fake : 20
mock : 20 | calls: [call('EUR')]
mock accepts any name: 99
autospec rejects it: Mock object has no attribute 'rate_typo'

What you see: The fake returned a real answer through real code. The plain mock accepted the misspelt method rate_typo and answered 99: a test using it would pass against code that calls a method that does not exist. The autospecced mock refused with AttributeError.

Mock: tests the call

Asserts how the code talked to the client.

mocked.pyruns offline
client = Mock()
client.rate.return_value = 2
price(client, "EUR", 10)
client.rate.assert_called_once_with(
    "EUR")

Fake: tests the result

A tiny working stand-in; assert the outcome.

faked.pyruns offline
client = FakeRates({"EUR": 2})
assert price(client, "EUR", 10) == 20

The shift: A mock checks the conversation; a fake lets you check the outcome, which survives refactoring.

Why: A test that asserts outcomes breaks only when behaviour breaks. A test that asserts calls breaks whenever the implementation changes.

Land it I prefer fakes for logic, a handful of real-dependency tests with Testcontainers for the data layer, and autospecced mocks only to check interactions or inject failures.

Likely follow-ups
"How do I keep a fake honest?"

By running one shared contract test against both the fake and the real thing. If the fake drifts from the real behaviour, the contract test fails.

The idea is to write the tests for the behaviour you rely on once, as a set of functions that take an implementation as a parameter. For a repository, that might be "saving an order and loading it gives the same order", "loading an unknown id raises NotFound" and "saving the same id twice replaces the first". Then one parametrised fixture supplies the in-memory fake and the real PostgreSQL repository, the second running in a container.

Every test in the contract file runs twice. The fake must pass all of them, which means it behaves like the real one for everything those tests cover. When production teaches you a new behaviour, you add a contract test, the fake fails, and you fix it.

The payoff is that thousands of fast tests built on the fake stay meaningful.

"Is an in-memory SQLite a good stand-in for PostgreSQL?"

For simple queries it sometimes works, but I do not trust it for anything that matters, because the differences are exactly the ones that cause production bugs.

SQLite and PostgreSQL differ in several ways. SQLite is flexible about types and will store text in an integer column. PostgreSQL enforces types. Locking is different: SQLite locks the whole database for writes, while PostgreSQL locks rows, so concurrency bugs and deadlocks appear on only one. JSON functions, array types, ON CONFLICT details, case sensitivity and date handling all differ too. A test that passes on SQLite says little about a query that uses jsonb or FOR UPDATE SKIP LOCKED.

So my split is: SQLite in memory is acceptable for a throwaway prototype or for code that is truly database-agnostic through an ORM and uses plain features. For the data layer of a service that runs on PostgreSQL, I test on PostgreSQL in a container, and I accept that this layer is slower and smaller.

"How do Testcontainers fit in CI?"

They need a container runtime, usually Docker, on the CI machine, and I use them in a way that keeps the cost low.

  1. One container per session: a session-scoped fixture starts PostgreSQL once and stops it at the end. Starting takes a few seconds, so doing it for every test would be far too slow.
  2. Clean state per test: each test gets either a transaction that is rolled back at the end, or a fresh schema or truncated tables from a function-scoped fixture. That keeps tests independent (Q139).
  3. Parallel workers: with pytest-xdist, each worker needs its own database, for example test_gw0, test_gw1, or its own container.

Hosted CI services usually provide Docker. Where they do not, a service container defined in the CI configuration does the same job. I mark these tests with @pytest.mark.integration so that developers can skip them locally when they only want a quick run, while CI always includes them.

"When is a mock the right tool?"

A mock is the right tool for checking an interaction or for causing a failure, which a fake does not do well.

Three clear cases:

  1. Side effects: the behaviour is "an email was sent once". A mock records the call, and assert_called_once_with proves it.
  2. Failures: a timeout, a connection reset or a 503 is hard to make a real service produce on demand. side_effect=TimeoutError makes the dependency fail exactly when you want, so you can test the retry or the fallback.
  3. Unavailable dependencies: a payment provider or an external system with no test mode cannot be run in tests.

I use create_autospec so that the mock keeps the real signature (Q135).

The warning sign is configuring the same mock in ten tests. That repeated set-up wants to be a small hand-written fake with a name, kept in one place and covered by a contract test. Then the tests read as behaviour, not as a script of expected calls.

Q138. "What is property-based testing (Hypothesis), and which bugs does it find?"

Reveal answer

Strong answer Instead of writing a few example inputs, you describe properties that must always be true, and Hypothesis generates hundreds of inputs, tries to break the property, and then shrinks the failing input to the smallest one that still fails.

It finds the bugs examples miss: empty inputs, zero, negative numbers, duplicates, Unicode, huge values, off-by-one at boundaries, rounding, and order-dependence. Good properties: "decode(encode(x)) == x" (round trip), "the total never changes when I split an amount", "sorting twice gives the same result", "the result is independent of input order", "the new implementation equals the old, slow one".

It does not replace example tests: a few examples document intent and pin known past bugs. Hypothesis adds breadth. Failing cases are saved in a local database and replayed next time, so a found bug stays found.

Picture it A function that splits an amount of cents between several parts, with a bug.

The setup: The property: the parts always add up to the original amount.

test_hyp.py · Hypothesis 6runs offline
from hypothesis import given, strategies as st

def split_total(cents, parts):
    base = cents // parts
    return [base] * parts            # ❌ forgets the remainder

@given(st.integers(min_value=0, max_value=10_000), st.integers(min_value=1, max_value=10))
def test_split_adds_up(cents, parts):
    assert sum(split_total(cents, parts)) == cents

Make the invisible visible: Run it.

pytest test_hyp.py -q · Python 3.12 (excerpt)runs offline

cents = 1, parts = 2

    @given(st.integers(min_value=0, max_value=10_000), st.integers(min_value=1, max_value=10))
    def test_split_adds_up(cents, parts):
>       assert sum(split_total(cents, parts)) == cents
E       assert 0 == 1
E        +  where 0 = sum([0, 0])
E        +    where [0, 0] = split_total(1, 2)
E       Failing test case: test_split_adds_up(
E           cents=1,
E           parts=2,
E       )

test_hyp.py:9: AssertionError
=========================== short test summary info ============================
FAILED test_hyp.py::test_split_adds_up - assert 0 == 1
1 failed in 0.38s

What you see: Hypothesis found a failing input and shrank it to the smallest one: cents=1, parts=2. The function returns [0, 0], which sums to 0: one cent vanished. The remainder of the integer division was forgotten. This is exactly the kind of money bug that a hand-picked example like "100 cents into 4 parts" never shows.

The fix: distribute the remainder: base, extra = divmod(cents, parts) and give one extra cent to the first extra parts.

Example test

Checks the cases you thought of.

example.pyruns offline
def test_split():
    assert sum(split(100, 4)) == 100

Property test

Checks the rule for many generated cases.

property.pyruns offline
@given(integers(0, 10_000), integers(1, 10))
def test_split(c, p):
    assert sum(split(c, p)) == c

The shift: Examples document intent; properties search for what you did not think of.

Why: A property states what must hold; the tool searches for a counterexample you would not think of.

Land it I describe Hypothesis as stating properties such as round trips and conservation of totals and letting the tool generate and shrink counterexamples, which finds boundary and duplicate-input bugs that hand-written examples miss.

Likely follow-ups
"How do I write good properties?"

I start from what must always be true, and I ask four questions about the function. If none of them gives a sentence, I use examples.

  1. Round trip: does an inverse exist? decode(encode(x)) == x is the standard one.
  2. Invariant: what stays the same? The total after splitting is the same as before. The number of items out equals the number in.
  3. Idempotence and order: does doing it twice equal doing it once, and does input order matter? sorted(sorted(x)) == sorted(x).
  4. Reference: is there a simple, slow version that is obviously right? Then the fast one must agree with it on every input.

A weak property is the trap. "The result is not None" passes for a function that always returns zero. A good property is tight enough that a wrong implementation would fail it. I check this by deliberately breaking the code, for example changing a < to <=, and seeing whether the property catches it within a few runs.

"What are strategies?"

A strategy is an object that describes how to generate one kind of value. You combine strategies to describe the inputs of your function, and Hypothesis draws random examples from them.

The basic ones are st.integers(min_value=0), st.text(), st.floats(allow_nan=False) and st.booleans(). Composite ones build on them: st.lists(st.integers(), min_size=1), st.tuples(...), and st.builds(Order, total=st.integers(1, 10_000)) for your own classes. You can also transform with .map(...) or filter with .filter(...).

The key discipline is to make the strategy produce valid input. If a function requires a positive quantity and the strategy generates negatives, the test fails for the wrong reason, and you learn nothing. Constrain at the source (min_value=1) instead of filtering afterwards, because Hypothesis can waste time throwing away most of its examples and then complains about it.

Start with simple strategies and widen them only as the property needs.

"Are Hypothesis tests flaky?"

They are random in the inputs, but reproducible when they fail, so they should not be flaky. If one is, the code or the test has a real problem.

When Hypothesis finds a failure, it shrinks the input to the smallest failing example, prints it, and saves it in a local database (the .hypothesis folder). On the next run it tries that saved example first, so a bug stays found until fixed. You can add @example(...) to keep a known case in the code forever.

The real causes of flakiness are in your code, not in Hypothesis:

  • output depending on the clock, randomness or global state that the test does not control;
  • a function slow enough to hit the 200 ms default deadline on a busy machine.

I set @settings(max_examples=...) to bound runtime, raise or disable the deadline for slow functions with a comment saying why, and keep the code under test deterministic for a given input.

"Where does it pay off most?"

It pays most where the input space is large, awkward and hard to list by hand, and where the rules are about relations, not single answers.

  • Parsers and serialisers: round trips find the odd Unicode character, the empty string and the escape that nobody thought of.
  • Money and rounding: "the allocated parts always sum to the total" breaks at certain amounts and part counts (Q144).
  • Dates, time zones and scheduling: days around daylight saving changes, month ends and leap years (Q143).
  • State machines: random sequences of operations expose illegal transitions. Hypothesis has a stateful testing feature for this.
  • Refactors: compare the new algorithm with the old one on random inputs.

Q141 uses it for reconciliation, where "every line is matched or reported, never lost" is a property that has to hold for all inputs.

It pays less on glue code, UI code and anything where a human decides the expected output. There, a few well-chosen examples are cheaper and clearer.

Q139 · Scenario. "Tests pass alone but fail when run together. Diagnose."

Reveal answer

Strong answer That pattern means tests share state, so one test's leftovers change another's result. Typical hidden shared state: a module-level dict or cache, a singleton, a global setting or environment variable changed and not restored, a database row, a file, the current time, a random seed, a class attribute or mutable default argument (Q3), a mock patched and never undone.

How to find it: run the failing test alone (passes), then run the whole file or folder and use -x to stop at the first failure. Then bisect: run the failing test with half of the other tests, and halve again until one polluting test is found. Randomising order (pytest-randomly) exposes such dependencies early and prints the seed to replay.

The fix: remove the shared state or reset it in a function-scoped fixture with yield teardown; use monkeypatch (which undoes itself), tmp_path (a fresh folder), a transaction rolled back after each test, and avoid module-level mutable globals in the code under test (pass dependencies in).

Picture it Two tests where the second silently depends on the first not having run.

test_order.pyruns offline
_cache = {}                           # module-level state shared by every test

def test_a_fills_cache():
    _cache["rate"] = 2
    assert _cache["rate"] == 2

def test_b_assumes_empty_cache():
    assert "rate" not in _cache

Make the invisible visible: Run both together, then the second one alone.

pytest test_order.py -q · Python 3.12runs offline
=========================== short test summary info ============================
FAILED test_order.py::test_b_assumes_empty_cache - AssertionError: assert 'ra...
1 failed, 1 passed in 0.30s
pytest test_order.py::test_b_assumes_empty_cache -qruns offline
.                                                                        [100%]

1 passed in 0.12s

What you see: Together: one failed, because the first test filled the module-level _cache. Alone: the same test passed. The result depends on what ran before it, which is the definition of a test that is not independent.

The fix: reset the shared state around each test with a fixture.

conftest.py · the fixruns offline
import pytest
import test_order

@pytest.fixture(autouse=True)
def clean_cache():
    test_order._cache.clear()      # ✅ start clean
    yield
    test_order._cache.clear()      # ✅ leave clean
pytest -q with the fixture · Python 3.12runs offline
2 passed in 0.14s

Why: Passing alone proves only that the test is correct in an empty world. Passing together proves it does not depend on its neighbours.

Land it I bisect to find the polluting test, then remove or reset the shared state with function-scoped fixtures and monkeypatch, and run tests in random order so such dependencies show up immediately.

Likely follow-ups
"How do I bisect quickly?"

I halve the suspects until one polluting test remains. That is a bisection, and it finds the culprit among 4,000 tests in about twelve runs.

  1. Confirm: run the failing test alone, then run it after the whole file or folder. If it fails only in the second run, something earlier pollutes it.
  2. Split: run the victim after the first half of the earlier tests, for example pytest tests/a.py tests/b.py::test_victim. If it fails, the culprit is in that half. If it passes, the other half.
  3. Repeat: halve again until a single test remains, then read it for global changes, cached values and files left behind.

Plugins automate the search. pytest-randomly prints a seed, and rerunning with the same seed (pytest -p randomly --randomly-seed=123) reproduces an order. Some tools can bisect the order for you, and the --lf flag reruns only the last failures. The manual halving is still the method I trust when the tools do not apply.

"What if it fails only in CI?"

Then I assume that CI differs from my laptop in one of four ways, and I check each one.

  1. Order: CI may shuffle tests or run them in separate processes, with a different order than yours. I reproduce with the same command and the same random seed.
  2. Parallelism: with pytest-xdist, tests that share a port, a temporary file path or one database run into each other. Each worker needs its own.
  3. Environment: a different time zone (CI often runs in UTC, laptops do not), locale, environment variables, or Python version.
  4. Clean state: CI starts from an empty database and no cache. A test that passed locally only because yesterday's data was still there fails.

I copy the exact command from the CI log, run it in the same container image, and compare environment variables. A test that depends on the current time or on the machine's time zone is the most common finding, followed by tests that depend on a file or row left by an earlier test.

"Can the code under test be the problem?"

Yes, often. The code can contain the hidden shared state itself, and the tests only reveal it.

A module-level cache, a singleton, a global settings object or a class attribute that collects values behaves the same way in production: its state depends on what ran before. Tests make the problem visible because they run hundreds of unrelated scenarios in one process, one after another. In production that coupling stays hidden until a rare mix of requests appears.

A typical case is a default argument of [] (Q3). The test that runs second gets what the first left behind.

The test fix, resetting the global in a fixture, repairs the symptom. The design fix is to pass the dependency in, so each caller and each test creates its own, and no hidden connection exists. I do the second whenever the change is small enough, and I leave a comment on the first when it is not.

"How do I prevent it?"

By making independence the default, so that a polluting test is found on the day it is written, not months later.

  1. Random order from the start: install pytest-randomly in CI. Every run uses a different order and prints its seed, so a hidden dependency fails soon and can be replayed.
  2. Fixtures with teardown: a test that changes the world uses a yield fixture, monkeypatch or tmp_path, so the clean-up happens even when the test fails.
  3. No module-level mutable state: no lists or dicts at the top of test files, and none in the code under test unless it is reset.
  4. A review rule: every test sets up what it needs and cleans what it changes.

I also run the suite in parallel regularly, since it exposes shared ports and files quickly. These habits cost little at the start and are very expensive to add to a suite of 4,000 tests that already depend on each other.

Q140. "How do you test async code?"

Reveal answer

Strong answer Test functions run as ordinary functions, so a plain def test cannot await. You need a plugin that runs async def tests inside an event loop. The two common ones are pytest-asyncio (mark with @pytest.mark.asyncio, or use auto mode) and anyio's pytest plugin (mark with @pytest.mark.anyio, which can also run the test under trio).

Then the test is just an async function: await the code under test and assert on the result. Async fixtures work the same way.

Things specific to async tests: use fakes that are async (or AsyncMock) for dependencies; control time with a fake clock or very small delays instead of real sleeps; test timeouts and cancellation explicitly (asyncio.timeout); test concurrency properties with gather and TaskGroup; and make tests fail loudly on leaked tasks, since an unawaited task can hide a bug (Q86).

Keep one event loop per test (the default) so tests do not share tasks.

Picture it Two async tests run through the anyio plugin.

test_async.py · pytest 9.1.1, anyio pluginruns offline
import asyncio, pytest

async def fetch_price(sku):
    await asyncio.sleep(0.01)
    return {"A1": 5}[sku]

@pytest.mark.anyio
async def test_fetch_price():
    assert await fetch_price("A1") == 5

@pytest.mark.anyio
async def test_gather():
    assert await asyncio.gather(fetch_price("A1"), fetch_price("A1")) == [5, 5]

Make the invisible visible: Run them.

pytest test_async.py -v · Python 3.12runs offline
collecting ... collected 2 items

test_async.py::test_fetch_price[asyncio] PASSED                          [ 50%]
test_async.py::test_gather[asyncio] PASSED                               [100%]


============================== 2 passed in 0.15s ===============================

What you see: Both tests ran under asyncio (the [asyncio] in the name shows the backend) and passed. Without the marker, pytest would only create the coroutine and report a warning that it was never awaited.

Make the invisible visible: A timeout test: the behaviour you most want to check.

timeout_test.py · Python 3.14runs offline
import asyncio, pytest

async def slow_lookup():
    await asyncio.sleep(5)

@pytest.mark.anyio
async def test_lookup_times_out():
    with pytest.raises(TimeoutError):
        async with asyncio.timeout(0.05):     # fast: no real 5-second wait
            await slow_lookup()
pytest test_timeout.py -q · Python 3.12runs offline
1 passed in 0.18s

Why: The deadline cancels the sleeping body at once, so the test takes 50 ms, not 5 s, and it checks the real timeout behaviour.

Land it I run async tests with the anyio or pytest-asyncio plugin, use async fakes, test timeouts and cancellation explicitly with short deadlines, and watch for leaked tasks.

Likely follow-ups
"pytest-asyncio or anyio?"

I choose by what the project already uses, and I use one plugin per project.

pytest-asyncio is the most common choice and is simple when the code uses only asyncio. anyio's plugin fits when the code is written against anyio, which FastAPI and Starlette use, or when you want to run the same tests under both asyncio and trio by parametrising the backend.

The setting that surprises people in pytest-asyncio is the mode. In strict mode, which is the default, only tests marked with @pytest.mark.asyncio run as async, and async fixtures need @pytest_asyncio.fixture. In auto mode, every async def test is picked up without a mark, which is convenient but means the plugin owns all coroutines. Details have changed between releases, so I check the documentation for the installed version.

I put the mode in the pytest configuration file so it is the same for everyone.

"What is AsyncMock?"

It is a mock whose calls return awaitables, so await client.get() works. A plain Mock does not do that.

An async function returns a coroutine, which the caller awaits. A normal mock returns an ordinary value or another mock, and awaiting that fails. AsyncMock (in unittest.mock) returns a coroutine that resolves to the return_value, and it records calls and supports side_effect too, so you can make the awaited call raise an error. It also has assert helpers such as assert_awaited_once_with.

q140_asyncmock.py outputruns offline
42
TypeError: object Mock can't be used in 'await' expression

The first line is the AsyncMock being awaited. The second is what a plain Mock does. I use create_autospec or patch(..., autospec=True) on an async function or class, since the mock then knows which methods are coroutines.

"How do I test code that uses asyncio.sleep for delays?"

I make the delay something the test can control, so no test waits for real seconds. There are three ways, in my order of preference.

  1. Inject it: give the function a sleep parameter that defaults to asyncio.sleep. The test passes an async no-op that records the delays it was asked for.
  2. Patch it: monkeypatch.setattr("pricer.client.asyncio.sleep", fake_sleep), with fake_sleep an async def that does nothing. Patch where it is used (Q135).
  3. Virtual clock: some libraries provide an event loop whose time jumps forward when everything is waiting, so a 30 second delay takes microseconds.

The aim is a retry with exponential back-off, for example 1, 2, 4 and 8 seconds, that runs in a few milliseconds in the suite. And by recording what the code asked to sleep, I can assert on the schedule: "it waited 1, 2, 4 seconds", which is better than a wall-clock check that depends on the machine.

"How do I test that concurrency really happens?"

I show that the calls overlapped by recording events, and I avoid asserting on how long it took.

Make the fake dependency log a "start" event when called, then wait on an asyncio.Event or a very short sleep, then log an "end" event. Run the code with three requests. If it is concurrent, the log reads start, start, start, end, end, end. If it is sequential, it reads start, end, start, end, start, end.

A stronger version blocks the first call on an event that only the second call sets. If the code runs the calls one after the other, the test deadlocks and a timeout fails it. That proves, without any timing, that the second call started while the first was still waiting.

The weak version asserts "three one-second calls finished in under 1.5 seconds". On a busy CI machine, a slow start-up or a garbage collection pause fails it at random, and people then add retries to tests. Ordering is deterministic, and elapsed time is not.

Q141 · Design. "Design the test strategy for a payment-reconciliation module."

Reveal answer

Strong answer Reconciliation matches the company's ledger lines against the bank's statement and reports what does not match. Errors cost real money and are often silent, so the strategy puts weight on invariants and exact money handling.

  1. Unit tests with examples: named cases for each rule: exact match, amount differs by one cent, date within tolerance, missing on either side, duplicate lines, refunds, currency mismatch. These document the business rules.
  2. Property tests (Hypothesis): conservation (every ledger line is matched or reported, nothing lost or counted twice), order independence, idempotence (reconciling twice gives the same answer), symmetry where it should hold.
  3. Money rules: Decimal or integer cents only; tests that fail if a float sneaks in; explicit rounding mode tests.
  4. Golden-file tests: real, anonymised statement files and the expected result, to catch parsing regressions (encodings, formats, signs).
  5. Integration tests: the real database in a container: transactions, unique constraints, concurrent runs, rollback on failure.
  6. Failure and replay: what happens when the run dies halfway; re-running must not double-post. Test idempotency keys.
  7. In production: reconciliation of the reconciliation: daily totals compared with an independent source, alerts on unmatched counts.

I would not rely on mocks for the money logic: it is pure code and needs no mocks at all.

Picture it A small reconciliation function with a duplicate-handling bug, and the property test that finds it.

recon.py · the buggy and the correct versionruns offline
from collections import Counter
from decimal import Decimal

def reconcile_buggy(ledger, bank):
    """Return (matched, only_in_ledger, only_in_bank) as amounts."""
    ledger_set, bank_set = set(ledger), set(bank)          # ❌ duplicates collapse
    return ledger_set & bank_set, ledger_set - bank_set, bank_set - ledger_set

def reconcile(ledger, bank):
    lc, bc = Counter(ledger), Counter(bank)
    matched = lc & bc
    return matched, lc - bc, bc - lc
test_recon.py · Hypothesisruns offline
from collections import Counter
from decimal import Decimal
from hypothesis import given, strategies as st
from recon import reconcile, reconcile_buggy

amounts = st.lists(st.decimals(min_value=Decimal("0.01"), max_value=Decimal("99.99"), places=2), max_size=8)

@given(amounts, amounts)
def test_nothing_lost_buggy(ledger, bank):
    m, l, b = reconcile_buggy(ledger, bank)
    assert len(ledger) == len(m) + len(l)          # every ledger line is matched or reported

@given(amounts, amounts)
def test_nothing_lost(ledger, bank):
    m, l, b = reconcile(ledger, bank)
    assert len(ledger) == sum(m.values()) + sum(l.values())
    assert len(bank) == sum(m.values()) + sum(b.values())

@given(amounts, amounts)
def test_order_does_not_matter(ledger, bank):
    assert reconcile(ledger, bank) == reconcile(list(reversed(ledger)), list(reversed(bank)))

Make the invisible visible: Run it.

pytest test_recon.py -q · Python 3.12 (excerpt)runs offline
>       assert len(ledger) == len(m) + len(l)          # every ledger line is matched or reported
E       AssertionError: assert 2 == (0 + 1)
E        +  where 2 = len([Decimal('0.01'), Decimal('0.01')])
E        +  and   0 = len(set())
E        +  and   1 = len({Decimal('0.01')})
E       Failing test case: test_nothing_lost_buggy(
E           ledger=[Decimal('0.01'), Decimal('0.01')],
E           bank=[],  # or any other generated value
E       )
FAILED test_recon.py::test_nothing_lost_buggy - AssertionError: assert 2 == (...
1 failed, 2 passed in 1.01s

What you see: The buggy version, which used sets, turns two identical 0.01 payments into one: assert 2 == (0 + 1), with the minimal failing input ledger=[0.01, 0.01], bank=[]. The correct version, based on Counter, passed both properties: nothing lost, and the order of inputs does not matter. The summary line shows one failure and two passes.

Why: Duplicate amounts are common in real payments (two identical coffees), and an example test written by a human often forgets them. A conservation property catches it automatically.

Land it I put the weight on property tests for conservation and idempotence, exact decimal money handling, golden files from real statements, a few real-database integration tests, and a production check of the totals, using mocks only at the edges.

Likely follow-ups
"How do you test rounding?"

With examples at the boundary of the chosen rule, and a property that the allocation always adds up. Float rounding is never used (Q144).

First, I pick the rounding mode on purpose, for example ROUND_HALF_UP for invoices, and write the half-cent cases as literal examples: 2.675 becomes 2.68 with half-up, and a banker's rounding (half to even) would give a different answer for 2.665. The test names the mode, so a change of mode fails loudly.

Second, the trouble with rounding is that the parts do not add up. Three items of 3.333 each round to 3.33, and their total of 9.99 is not 10.00. So the test is a Hypothesis property: for any total and any number of parts, after the allocation rule is applied, the parts sum exactly to the total, and no part differs from another by more than one cent.

Third, a test that passes a float into the money code must raise, so no float sneaks in.

"How do you test idempotency?"

By running the same reconciliation twice and asserting that the second run changes nothing. Then I kill a run in the middle and rerun it.

  1. Run twice: reconcile one statement, record a snapshot of the matched table, the ledger entries and the report, then run again with the same input. The snapshots must be identical, with no new ledger entries.
  2. Kill halfway: inject a failure after half of the lines, for example with a mock that raises on the 50th call. Check the database: either the whole batch rolled back, or the finished part is committed with a marker. Then rerun and check that the final state equals a clean single run.
  3. Idempotency key: submit the same key twice and confirm that the second call returns the first result.

Idempotency matters here because reruns are normal: a job times out and the scheduler retries. Without it, a rerun posts the same money twice.

"How do you get realistic test data?"

By mixing three sources, and by keeping a rule that production bugs become permanent tests.

The first source is real statements made safe: the account numbers and names are replaced, but amounts, dates, line order, encodings and odd formats are kept. These become golden files. The second is a library of nasty cases found in production. A statement with a duplicate line, a refund that arrives before its payment, or a line with a negative zero amount all come from real incidents, and each is added as a named test the day it is fixed, so the suite grows from real failures.

The third is Hypothesis. It generates thousands of random ledgers and statements, with a matching one built by a simple generator, and checks the invariants.

Why not use real data directly? Customer privacy and the law, and a data set that nobody understands, which makes failures hard to read. Small synthetic and anonymised cases are easier to reason about.

"How do you measure test quality?"

Not with one number. Coverage is a floor, and the better measures ask whether the tests would notice a bug.

  1. Coverage: branch coverage on the module tells me which code never runs in tests. A line that runs does not mean its result was checked, so I use it to find gaps, not to declare victory.
  2. Mutation testing: a tool such as mutmut changes the code, for example > to >= or + to -, and reruns the tests. If the tests still pass, that mutant survived and the tests missed a possible bug. I run it on the money code only, because it is slow.
  3. Incidents: after every production issue I ask whether the suite should have caught it and add the test.

For this module I accept a slower suite, since a missed reconciliation error costs money and may not be noticed for weeks. A surviving mutant in the allocation code is a reason to write another test.

Drill · Production scenarios and code review

Short, concrete scenarios with a known culprit, and the two questions that sum up seniority: how you would port a service and what you would put on a review checklist.

Q142 · Scenario. "A queue worker silently stops processing; the logs show nothing. Investigate."

Reveal answer

Strong answer "Silently stops" in Python usually means an exception killed the worker loop and the error went somewhere nobody reads. In a thread, an uncaught exception ends only that thread; the process stays alive, so health checks that only test "is the process up" stay green. In asyncio, an exception in a background task that nobody awaits is reported only when the task object is garbage-collected (Q86).

Investigation order. 1. Is the process alive and is the worker alive? Dump the stacks (py-spy dump): if no thread is in the consume loop, it died. 2. Look at stderr, not just the log file: the default thread traceback goes to stderr, which a container platform may not collect.

3. Look at the queue: is depth growing and is the oldest message getting older? 4. Check for a stuck worker rather than a dead one: a worker blocked forever in a call without a timeout looks the same from outside.

The fix has four parts: catch exceptions inside the loop, log with traceback, and send the bad message to a dead-letter store; install threading.excepthook (and an asyncio done-callback) so a crash is logged and counted; run a supervisor that restarts dead workers; and add a heartbeat metric and alert on queue age, so silence becomes an alarm.

Picture it The silent death, then the robust version, both run for real.

The setup: A worker reads strings and converts them to integers. The second item, "abc", raises ValueError.

silent_worker.py · Python 3.14 (excerpt)runs offline
import threading, time, queue, asyncio, logging

q = queue.Queue()
def worker():
    while True:
        item = q.get()
        print("  processing", item)
        int(item)                       # raises ValueError on "abc"

t = threading.Thread(target=worker, name="queue-worker", daemon=True)
t.start()
for item in ("1", "abc", "3"):
    q.put(item)
time.sleep(0.3)
print("worker alive?", t.is_alive(), "| items still waiting:", q.qsize())

print("--- asyncio flavour: exception in a task nobody awaits")
async def failing():
    raise ValueError("bad row")
async def main():
output · Python 3.14 (shortened)runs offline
  processing 1
  processing abc
Exception in thread queue-worker:
  ...(10 lines of traceback)...
ValueError: invalid literal for int() with base 10: 'abc'
worker alive? False | items still waiting: 1

What you see: Item "1" was processed, then the worker died on "abc". The only trace is a traceback on stderr. The thread is dead (worker alive? False) and item "3" waits forever, while the main program carries on normally.

Make the invisible visible: The fixed worker: errors are caught inside the loop, logged with a traceback, and the item goes to a dead-letter list.

robust_worker.py · Python 3.14runs offline
q = queue.Queue(); dead_letter = []
last_beat = time.monotonic()

def worker():
    global last_beat
    while True:
        item = q.get()
        try:
            int(item)
            print("  processed", item)
        except Exception:
            log.exception("bad item %r sent to dead-letter", item)   # ✅ logged with traceback
            dead_letter.append(item)
        finally:
            last_beat = time.monotonic()          # heartbeat: a monitor alerts if this goes stale
            q.task_done()

t = threading.Thread(target=worker, name="queue-worker", daemon=True); t.start()
for item in ("1", "abc", "3"):
    q.put(item)
q.join()
print("worker alive?", t.is_alive(), "| dead-letter:", dead_letter, "| heartbeat age: %.2f s" % (time.monotonic() - last_beat))
output · Python 3.14runs offline
ERROR queue-worker bad item 'abc' sent to dead-letter
Traceback (most recent call last):
  File "robust_worker.py", line 13, in worker
    int(item)
    ~~~^^^^^^
ValueError: invalid literal for int() with base 10: 'abc'
  processed 1
  processed 3
worker alive? True | dead-letter: ['abc'] | heartbeat age: 0.00 s

What you see now: The bad item was logged with its traceback and put aside, items 1 and 3 were both processed, the worker is still alive, and the heartbeat is fresh.

Worker loop that can die

One exception ends the thread silently.

fragile.pyruns offline
while True:
    item = q.get()
    handle(item)   # raises -> dead

Failure inside the loop

Log it, set it aside, keep going.

robust.pyruns offline
while True:
    item = q.get()
    try:
        handle(item)
    except Exception:
        log.exception("bad %r", item)

The shift: Treat a bad message as data to record, not as a reason for the worker to die.

Why: A failure inside the loop is data to record; a failure that escapes the loop is a dead worker. Monitoring the heartbeat or queue age turns any remaining silent failure into an alert.

Land it I assume the loop died on an uncaught exception, confirm with a stack dump and queue age, and fix it by catching and logging inside the loop with a dead-letter path, plus a supervisor, an excepthook and a heartbeat alert.

Likely follow-ups
"Which metrics would have caught it earlier?"

The ones that show the loop has stopped, not just the load. A raw queue depth is a poor signal, because depth also rises at busy times.

  1. Age of the oldest message: if the oldest message has waited 20 minutes and the number keeps rising, nobody is consuming.
  2. Messages processed per minute: a drop to zero while the queue is not empty is a dead worker. Alert on a rate of zero when depth is above zero.
  3. Heartbeat: each worker updates a timestamp or increments a counter every loop, even when idle. A stale heartbeat identifies which worker died.

I alert on the age rising for several minutes, so a short burst does not page anyone. In this incident, the "processed per minute" graph would have fallen to a flat line at the time of the crash, and the alert would have fired within minutes instead of the next morning.

"What does threading.excepthook do?"

It is a hook that Python calls when a thread ends because of an exception that nobody caught. You can replace it with your own function, and that is how thread crashes reach your normal tools.

By default, Python prints the traceback to stderr and the thread ends. The process continues, which is why the failure was silent. In a container, stderr may not be collected, or it is mixed with other output.

You set threading.excepthook = my_hook. The function receives an object with exc_type, exc_value, exc_traceback and thread. A good hook does three things:

  1. Log: write the traceback through the standard logging system with the thread's name, so it carries the usual fields.
  2. Count: increment a metric such as worker_crashes_total that an alert watches.
  3. React: set a flag that makes the health check fail, so the platform restarts the process (below).

It does not catch exceptions in asyncio tasks. Those need a done-callback or the loop's exception handler.

"How do you tell "dead" from "stuck"?"

A stack dump tells them apart in seconds, and the fix differs for each.

With py-spy dump --pid <pid>, which reads a running process without stopping it, you see every thread's stack. A dead worker has no thread in the consume loop at all: the thread is gone, or the main thread sits idle. A stuck worker has a thread sitting in a call, for example in socket.recv, in lock.acquire or inside a database driver, at the same line in two dumps a minute apart.

From the outside they look the same: the queue grows and nothing is processed. But the fixes are different. A dead worker needs the catch-and-log, the excepthook and a supervisor. A stuck worker needs a timeout on every external call, since a call without one can wait forever, and a watchdog that raises an alarm when the heartbeat has not moved.

I take the dump before restarting anything, because a restart clears the evidence.

"Should the process just exit when the worker dies?"

Often yes, and in a container platform it is usually the safest design. Let the orchestrator, such as Kubernetes or systemd, restart the whole process.

The worst state is a live process with a dead worker: it passes the "is it running" check, receives traffic or messages, and does nothing. A process that exits is obvious, and the platform restarts it within seconds with a clean state, so a restart often repairs the leaked connection or the corrupt in-memory state that caused the crash.

The way to do this with threads is to have the worker or the excepthook set a flag. The health endpoint then reports unhealthy, or the main thread sees the flag and exits with a non-zero code.

Two cautions. First, restart loops: if the cause is a poison message that crashes every worker, the process restarts forever. The fix is the dead-letter path, which removes the bad message after a few attempts. Second, finish in-flight work first where you can, with a graceful shutdown.

Q143 · Scenario. "A scheduler built on datetime.now() fires at the wrong time across time zones. Fix it."

Reveal answer

Strong answer datetime.now() returns a naive datetime: a date and a time with no zone attached. It means "the clock on this machine", whatever its zone. Servers in different regions, or a server whose zone changes, interpret the same number differently. A job set for 09:00 means 09:00 where? And twice a year, local time jumps (daylight saving time), so some local times do not exist or happen twice.

The fix is a rule with three parts. Store and compute in UTC with timezone-aware datetimes (datetime.now(timezone.utc)). Keep the user's zone as a name ("America/New_York"), not as an offset, because the offset changes with daylight saving. Convert to local time only for display and for "every day at 09:00 local" rules, using zoneinfo.

For a recurring local-time rule, compute each next fire time from the rule and the zone each time, then convert to UTC for storage. Never add 24 hours and call it "tomorrow 09:00".

Picture it Naive versus aware datetimes, and the missing hour of a daylight-saving change.

tz_scheduler.py · Python 3.14runs offline
from datetime import datetime, timezone, timedelta
from zoneinfo import ZoneInfo
import os, time

naive = datetime(2026, 3, 29, 1, 30)             # "01:30" in whose zone?
print("naive:", naive, "tzinfo =", naive.tzinfo)
print("naive compared with aware ->", end=" ")
try:
    naive < datetime.now(timezone.utc)
except TypeError as e:
    print("TypeError:", e)

berlin = ZoneInfo("Europe/Berlin")
before = datetime(2026, 3, 29, 1, 30, tzinfo=berlin)      # DST starts at 02:00 -> 03:00
after = before + timedelta(hours=1)
print("wall-clock +1h:", after.isoformat(), "| real elapsed:", (after.astimezone(timezone.utc) - before.astimezone(timezone.utc)))
print("in UTC:", before.astimezone(timezone.utc).isoformat(), "->", after.astimezone(timezone.utc).isoformat())
nonexistent = datetime(2026, 3, 29, 2, 30, tzinfo=berlin)
print("02:30 does not exist; zoneinfo says:", nonexistent.isoformat(), "=", nonexistent.astimezone(timezone.utc).isoformat(), "UTC")
fire = datetime(2026, 7, 1, 9, 0, tzinfo=ZoneInfo("America/New_York"))
print("store:", fire.astimezone(timezone.utc).isoformat(), "+ the zone name 'America/New_York'")

Make the invisible visible: Run it.

output · Python 3.14runs offline
naive: 2026-03-29 01:30:00 tzinfo = None
naive compared with aware -> TypeError: can't compare offset-naive and offset-aware datetimes
wall-clock +1h: 2026-03-29T02:30:00+01:00 | real elapsed: 1:00:00
in UTC: 2026-03-29T00:30:00+00:00 -> 2026-03-29T01:30:00+00:00
02:30 does not exist; zoneinfo says: 2026-03-29T02:30:00+01:00 = 2026-03-29T01:30:00+00:00 UTC
store: 2026-07-01T13:00:00+00:00 + the zone name 'America/New_York'

What you see: A naive datetime has tzinfo = None, and comparing it with an aware one raises TypeError, which is Python protecting you. On 29 March 2026 Berlin skips from 02:00 to 03:00, so 02:30 does not exist: Python accepts it and gives it the old offset, which is the same instant as 01:30 UTC, that is 03:30 local. And a rule like "9:00 New York on 1 July" is stored as 13:00 UTC together with the zone name.

Naive: the machine's clock

Meaning depends on where the code runs.

naive.pyruns offline
now = datetime.now()
run_at = now.replace(hour=9,
                     minute=0)
# 9:00 in which zone?

Aware: zone-explicit

Compute in a named zone, store UTC.

aware.pyruns offline
tz = ZoneInfo(user.zone)
local = datetime.now(tz).replace(
    hour=9, minute=0)
run_at = local.astimezone(UTC)

The shift: A time without a zone is ambiguous; a time with a zone name can always be converted to one exact instant.

Why: An instant is unambiguous in UTC. Local time is a presentation of an instant under a set of rules that change, so keep the rules (the zone name) and recompute.

Land it I store and compute in UTC with aware datetimes, keep the user's zone as an IANA name from zoneinfo, convert to local time only for display and for recurring local-time rules, and never use naive datetimes.

Likely follow-ups
"Why store the zone name instead of the offset?"

Because an offset such as +01:00 is true for one date only, while a zone name carries the rules that change over the year.

Europe/Berlin is +01:00 in winter and +02:00 in summer, and the switch dates move from year to year. If you store the offset you saw at signup, every date in the other half of the year is wrong by an hour. The zone name lets zoneinfo calculate the correct offset for any date.

There is another reason: the rules change. Governments change daylight saving and sometimes abolish it, with only a few months of notice. The rules live in the IANA time zone database, and Python's zoneinfo reads them from the operating system or from the tzdata package. Where the OS has no data (Windows, some slim containers) you must install tzdata and keep it updated.

So I store the name for the user's intent ("9:00 in Berlin") and UTC for the moment ("this fires at 07:00 UTC"),.

"What about ambiguous times (the hour that happens twice)?"

When clocks go back, a local time such as 01:30 happens twice, once before and once after the change. Python resolves it with the fold attribute.

On 1 November 2026, New York clocks go back from 02:00 to 01:00, so 01:30 occurs twice. fold=0 means the first occurrence and fold=1 the second. Here is the real output of the two cases:

q143_fold.py outputruns offline
0 2026-11-01T01:30:00-04:00 -> 2026-11-01T05:30:00+00:00
1 2026-11-01T01:30:00-05:00 -> 2026-11-01T06:30:00+00:00

The two UTC instants are an hour apart. A scheduler that says "run at 01:30 local" must decide a policy: run once, at the first, which is the usual choice, and write it down. The opposite problem in spring is a time that does not exist at all (02:30 when clocks jump from 02:00 to 03:00). Policy there is to run at the next valid moment. I test both dates for at least two zones.

"How do I test this?"

By taking the clock out of the code and testing the dangerous dates on purpose.

  1. Inject the clock: the scheduler asks a clock object for "now" (a function returning an aware datetime). The test passes a fake that returns any instant I choose, so no test waits for 09:00.
  2. Dangerous dates: cases for the spring jump, the autumn repeat and a day with 23 and 25 hours, in at least two zones, for example America/New_York and Europe/Berlin, which change on different dates.
  3. Odd offsets: Asia/Kolkata is +05:30, so code that assumes whole hours fails there, and Asia/Kathmandu is +05:45.
  4. Property test: Hypothesis generates instants and zones and checks that converting to local time and back to UTC gives the same instant.

The aim is that the next daylight saving change is a date in the test suite, not a surprise at 3 a.m.

"Does the database matter?"

Yes. A correct program can still lose the time zone in the database, so I choose a column type that stores an instant.

In PostgreSQL, timestamptz stores a point in time. It does not keep the zone you sent: it converts to UTC on the way in and converts to the session's zone on the way out. The plain timestamp stores a wall-clock reading with no zone, and two servers with different zones then read the same value as different moments.

I pair that with these habits: send aware datetimes from Python so the driver converts correctly, set the connection time zone to UTC, and put the user's zone name in a separate column (for example zone text) because timestamptz does not remember it.

For a future event such as "every Monday at 9:00 Berlin time", I store the rule and the zone and compute the next UTC instant.

Q144 · Scenario. "An invoice total is off because 0.1 + 0.2 != 0.3. Fix money handling."

Reveal answer

Strong answer Python's float stores numbers in binary. The fractions 0.1 and 0.2 have no exact binary form, just as one third has no exact decimal form, so each is stored as a very close neighbour. The error is tiny, about one part in 1016, but it appears in comparisons and when many values are added and rounded.

For money use Decimal built from strings, or integer cents. Decimal does exact decimal arithmetic and lets you choose the rounding mode explicitly. Integer cents are simple and fast, and fit a database column, but you must handle currencies with other minor units (yen has none, some currencies have three).

Rules I enforce: never construct Decimal from a float (Decimal(0.1) keeps the float's error); round only at defined points with quantize and a named mode (ROUND_HALF_UP for invoices in most jurisdictions); store the currency with the amount; allocate remainders explicitly when splitting (give the extra cent to someone, and test that the parts add up); and know that Python's round() uses banker's rounding (half to even).

Picture it The float surprises and the Decimal fix.

money_decimal.py · Python 3.14runs offline
from decimal import Decimal, ROUND_HALF_UP
print("float :", 0.1 + 0.2, "| == 0.3 ?", 0.1 + 0.2 == 0.3)
print("sum of 10 x 0.10 as float:", sum([0.10] * 10), "| == 1.0 ?", sum([0.10] * 10) == 1.0)
print("Decimal:", Decimal("0.1") + Decimal("0.2"), "| == 0.3 ?", Decimal("0.1") + Decimal("0.2") == Decimal("0.3"))
print("Decimal(0.1) built from a float keeps the error:", Decimal(0.1))
print("round(2.675, 2) ->", round(2.675, 2), "| round(0.5) ->", round(0.5), "| round(1.5) ->", round(1.5), "| round(2.5) ->", round(2.5))
print("quantize HALF_UP:", Decimal("2.675").quantize(Decimal("0.01"), ROUND_HALF_UP))
cents = 1999 * 3
print("integer cents:", cents, "->", f"{cents // 100}.{cents % 100:02d}")

Make the invisible visible: Run it.

output · Python 3.14runs offline
float : 0.30000000000000004 | == 0.3 ? False
sum of 10 x 0.10 as float: 1.0 | == 1.0 ? True
Decimal: 0.3 | == 0.3 ? True
Decimal(0.1) built from a float keeps the error: 0.1000000000000000055511151231257827021181583404541015625
round(2.675, 2) -> 2.67 | round(0.5) -> 0 | round(1.5) -> 2 | round(2.5) -> 2
quantize HALF_UP: 2.68
integer cents: 5997 -> 59.97

What you see: 0.1 + 0.2 is 0.30000000000000004, not equal to 0.3. Ten additions of 0.10 happened to give exactly 1.0, which shows why the bug is intermittent. Decimal("0.1") + Decimal("0.2") equals 0.3 exactly, but Decimal(0.1) built from a float shows the long binary error. round(2.675, 2) gave 2.67, not 2.68, because 2.675 is stored slightly below; and round(0.5), round(1.5), round(2.5) gave 0, 2, 2: half rounds to even. The explicit quantize with ROUND_HALF_UP gave the 2.68 an invoice expects.

float: fast, inexact

Binary fractions; errors accumulate.

float.pyruns offline
total = 0.0
for line in lines:
    total += line.price * line.qty
round(total, 2)   # 2.675 -> 2.67

Decimal: exact decimals

Built from strings, rounded on purpose.

decimal.pyruns offline
total = Decimal("0")
for line in lines:
    total += line.price * line.qty
total.quantize(Decimal("0.01"),
               ROUND_HALF_UP)

The shift: Money is counted in whole decimal units with a rounding rule you chose, not in binary approximations.

Why: The bug is not randomness. The same inputs give the same wrong answer; it only shows up when a value lands on a representation boundary.

Land it I use Decimal built from strings or integer cents for money, round only at defined points with an explicit mode, store the currency alongside, and test allocation so parts always add up.

Likely follow-ups
"Decimal or integer cents?"

I choose by what the arithmetic needs and where the number is going. Many systems use both, each at its own boundary.

Integer cents (more exactly, minor units) are fastest and simplest for adding, comparing, storing and sending. A database column of bigint holds them exactly, and an API that sends 1999 has no formatting trap. The cost is that you must know each currency's exponent: yen has none, dinar-type currencies have three.

Decimal is better when you multiply: a tax rate of 7.25%, a currency conversion, a percentage discount, or prices with more than two places such as a fuel price. It keeps the exact decimal digits and lets you choose the rounding mode.

A common design: store and move integer minor units, convert to Decimal for the calculation, round once with a named mode, and convert back. The trap is mixing the two without a clear boundary, so that someone adds cents to dollars. I pick one representation per layer and write the conversion in one function.

"How do I split 100.00 between three people?"

You work in cents and use divmod, then give the leftover cents to specific people by a written rule. Here is the real output:

q144_split.py outputruns offline
3333 1 [3334, 3333, 3333]
  1. Divide: 100.00 is 10000 cents. divmod(10000, 3) gives 3333 each and a remainder of 1.
  2. Distribute the remainder: one extra cent goes to the first person, giving 3334, 3333 and 3333, which sum to 10000.
  3. Write the rule down: who gets the extra cents is a business decision (the first, the largest share, round-robin by id) and must be the same on every run, so statements stay reproducible.

Dividing 100.00 by 3 and rounding each part gives 33.33 three times, and a cent vanishes. I test with a Hypothesis property that for any total and any number of parts, the parts sum exactly to the total (Q138).

"What precision does Decimal use?"

By default a context of 28 significant digits, which is plenty for money. The point to know is that the context is shared and applies to every operation.

Significant digits are counted across the whole number, so precision is rarely a problem. The setting that matters more is rounding: the default mode is ROUND_HALF_EVEN, and it applies when an operation has more digits than the precision allows. quantize with an explicit mode is how you round to cents on purpose.

The context is per thread, so changing it in one place changes it for later code in the same thread. That is a hidden global. I avoid getcontext().prec = ... in application code, and use with localcontext() as ctx: for a special calculation. The change then ends at the end of the block.

The better habit is to give no operation the chance to depend on the context: build values from strings, and call quantize at defined points with a named mode.

"Is a frozen dataclass Money worth it?"

Yes. A small Money class moves the rules from many scattered places to one place, and the type checker helps to enforce them.

The class holds amount: Decimal and currency: str, and it is a frozen dataclass (see Q10 and the pat-frozen-value idiom), so a value cannot change after creation and it can be a dict key. It defines __add__ so that adding USD to EUR raises an error instead of producing a meaningless number. It rejects floats in its constructor. It has one method for allocating, split(n), that returns parts which sum to the total.

Without it, a function that takes amount and currency as two loose arguments can swap them, forget the currency or mix units, and the interpreter does not notice.

The costs are small: a bit of code and a conversion at the edges, where JSON and the database speak plain numbers.

Q145 · Scenario. "Logs are unreadable under load and carry no request ids. Design the logging."

Reveal answer

Strong answer I design for the person reading logs at 3 a.m. during an incident, who needs to filter by one request across many lines and many services.

  1. Structured output: one JSON object per line with timestamp, level, logger, message, request_id, and fields such as user, tenant and duration. Machines can then filter and count.
  2. Request id from a context variable: set once in middleware (reuse the incoming X-Request-ID header or create one), read by a logging filter, so every line carries it with no parameter passing (Q90). Pass it on in outgoing calls to correlate services.
  3. Levels with meaning: ERROR means someone should look; WARNING is unexpected but handled; INFO is business events; DEBUG is off in production. Use log.exception to keep tracebacks.
  4. Do not slow the request: logging to a slow sink inside the request thread adds latency. Use a QueueHandler so a separate thread writes.
  5. Control volume: no per-item logging in hot loops; sample noisy events; rate-limit repeated errors.
  6. Safety: never log secrets, tokens or full card numbers; scrub personal data.
  7. Tie to the rest: metrics for counts and rates, traces for timing across services; logs for the details.

Under load, the structure and the id matter more than the text: a thousand interleaved lines are only readable if each carries its request id.

Picture it Structured JSON with a request id from a context variable, and the cost of a slow log sink.

json_logging.py · Python 3.12runs offline
import contextvars, json, logging, sys

request_id = contextvars.ContextVar("request_id", default="-")

class ReqIdFilter(logging.Filter):
    def filter(self, record):
        record.request_id = request_id.get()
        return True

class JsonFormatter(logging.Formatter):
    def format(self, r):
        return json.dumps({"ts": self.formatTime(r, "%H:%M:%S"), "level": r.levelname,
                           "logger": r.name, "request_id": r.request_id, "msg": r.getMessage()})

h = logging.StreamHandler(sys.stdout); h.setFormatter(JsonFormatter()); h.addFilter(ReqIdFilter())
log = logging.getLogger("pricer"); log.addHandler(h); log.setLevel(logging.INFO)

def handle(rid):
    request_id.set(rid)
    log.info("pricing started")
    try:
        1 / 0
    except ZeroDivisionError:
        log.exception("pricing failed")      # keeps the traceback in the record

handle("req-123")
output · Python 3.12runs offline
{"ts": "15:36:59", "level": "INFO", "logger": "pricer", "request_id": "req-123", "msg": "pricing started"}
{"ts": "15:36:59", "level": "ERROR", "logger": "pricer", "request_id": "req-123", "msg": "pricing failed"}

What you see: Each line is one JSON object with the request id, even though the code never passed the id to the logger. The error line was written by log.exception, which also keeps the traceback in the record.

Make the invisible visible: Does it matter that logging happens in the request thread? A handler that takes 0.2 ms per record, called 2,000 times.

logging_queue.py · Python 3.14runs offline
import logging, logging.handlers, queue, time

class SlowHandler(logging.Handler):          # stands in for a network or disk handler
    def emit(self, record):
        time.sleep(0.0002)

def run(logger, n=2000):
    t = time.perf_counter()
    for i in range(n):
        logger.info("request %d", i)
    return (time.perf_counter() - t) / n * 1e6

direct = logging.getLogger("direct"); direct.setLevel(logging.INFO); direct.addHandler(SlowHandler())
q = queue.SimpleQueue()
queued = logging.getLogger("queued"); queued.setLevel(logging.INFO); queued.addHandler(logging.handlers.QueueHandler(q))
listener = logging.handlers.QueueListener(q, SlowHandler()); listener.start()
print(f"direct to the slow handler : {run(direct):7.1f} us per log call (the request thread waits)")
print(f"through QueueHandler       : {run(queued):7.1f} us per log call (the listener thread waits)")
listener.stop()
output · Python 3.14runs offline
direct to the slow handler :   288.5 us per log call (the request thread waits)
through QueueHandler       :    16.5 us per log call (the listener thread waits)
# measured on the course machine; your numbers will differ

What you see: Writing directly cost the request thread 288 microseconds per call, because it waited for the slow sink. Through a QueueHandler the request thread paid 16.5 microseconds and a listener thread did the slow work. For a handler that writes over the network, the difference is the difference between a fast and a slow endpoint.

print in the request path

Unstructured, no id, can block.

print.pyruns offline
print("saved order", order.id)

Structured, with context

JSON line with the request id.

logging.pyruns offline
log.info("order saved",
         extra={"order_id": order.id})
# request_id added by a filter

The shift: A log line is a record for a machine first and a person second.

Why: A log call is part of the request. If it can block, it must not run in the request's critical path.

Land it I log one JSON object per line with a request id taken from a context variable, give levels a defined meaning, write through a queue so logging cannot slow requests, control volume and never log secrets.

Likely follow-ups
"Where does the request id come from?"

From the edge of the system: the first service that receives the request either reuses an id sent by the caller or creates a new one, and passes it on to everything it calls.

In a middleware, I read the incoming X-Request-ID header, or the traceparent header if the platform uses distributed tracing. If neither exists, I create a UUID. I then store it in a ContextVar (Q90), so that it follows the request through await calls and threads started with context copying, without being passed as a parameter. A logging filter reads the variable and adds it to every record. The response header carries it too, so a user can quote it.

For outgoing calls, the HTTP client adds the same header, and queue messages carry it as a field.

The result is that one search for that id in the log system returns the whole story across services, in order. I limit the length and characters of incoming ids, since a public client could send anything.

"print or logging?"

Use logging. print is for quick experiments and should not remain in production code.

The standard library gives what you need in an incident. Levels let you keep DEBUG off in production and turn it on for one module without editing code. Handlers decide where records go: a file, stdout, a queue. Formatters decide the shape, such as JSON. Filters attach context like the request id. All of that is configured in one place at start-up.

By comparison, print has none of it. It cannot be switched off by level, it has no structure, and it blocks when the pipe is full.

It is a few lines of set-up to get a JSON formatter and a filter, and that is a small cost compared with an incident in which the logs cannot be searched.

"What about libraries such as structlog?"

They make structured, context-bound logging comfortable, and they sit on top of the standard library, so you are not forced to choose.

structlog lets you attach fields to a logger and keep them: log = log.bind(order_id=7) and then every later line from log includes order_id=7. It has processors, small functions that run in a chain to add the timestamp, the request id and the level, and a final renderer, JSON in production and coloured text on a laptop. It can forward to logging handlers, so existing libraries' messages follow the same format.

The standard library alone is enough, as the design above shows: a JSON formatter, a context filter and extra= fields for structure. I choose structlog when many call sites bind rich context and the team will use it consistently, since it reduces repeated arguments.

The cost is one more dependency and a second configuration to learn. I start with the standard library and move when repeated extra= dictionaries become a burden.

"How do I avoid log volume costs?"

By deciding what is worth a line, then controlling the number of lines and their lifetime. Log cost scales with bytes stored and indexed.

  1. Levels with a budget: INFO only for business events (order placed, payment captured). DEBUG stays off. No log lines in hot loops.
  2. Sampling: for events that happen thousands of times a second, such as cache hits, log one in a hundred or aggregate them into a metric instead.
  3. Rate limiting: a failing dependency can repeat the same error 10,000 times a minute. Log it once with a count.
  4. Retention by level: keep ERROR for months, INFO for weeks, DEBUG for days.

I measure it. Count the bytes per request, for example by dividing the daily log volume by the daily request count. A request that writes 50 lines is probably logging too much. Metrics carry counts and rates cheaply, and logs carry the detail for the unusual cases.

Q146 · Scenario. "Code review: except Exception: pass around a database call. What do you say?"

Reveal answer

Strong answer I say it clearly and politely: this hides every possible failure, and the system will report success when it did not save anything.

Specifically: the database call can fail for many reasons: a duplicate key, a lost connection, a timeout, a bug in the query, a programming error such as a misspelt column. The handler treats all of them as "nothing happened". The caller continues with data it believes is saved, so the failure appears later, somewhere unrelated, as missing orders or wrong totals, with no log line to follow.

What I ask for instead: catch the specific exception you expect and can handle (for example IntegrityError for an idempotent duplicate), handle it meaningfully (ignore with a log line, retry, or return a clear error), and let everything else propagate to a layer that logs it and fails the request or job. If something must be swallowed, log with exc_info and add a comment explaining why.

Also mention: except Exception already does not catch KeyboardInterrupt, but a bare except: does, and is worse.

Picture it The pattern, what it does to a duplicate order, and the review fix.

except_pass.py · Python 3.14runs offline
import sqlite3

def save(conn, order_id, total):
    try:
        conn.execute("INSERT INTO orders VALUES (?, ?)", (order_id, total))
    except Exception:
        pass                                  # ❌ TRAP

conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE orders (id INTEGER PRIMARY KEY, total REAL)")
save(conn, 1, 9.5)
save(conn, 1, 9.5)                            # duplicate key: silently dropped
save(conn, 2, 5)
conn.execute("DROP TABLE orders") if False else None
print("rows:", conn.execute("SELECT COUNT(*) FROM orders").fetchone()[0], "- and no error anywhere")

import logging
logging.basicConfig(format="%(levelname)s %(message)s")
def save_better(conn, order_id, total):
    try:
        conn.execute("INSERT INTO orders VALUES (?, ?)", (order_id, total))
    except sqlite3.IntegrityError:
        logging.warning("duplicate order %s ignored (idempotent retry)", order_id)   # ✅ named, logged
save_better(conn, 1, 9.5)

Make the invisible visible: Run it.

output · Python 3.14runs offline
rows: 2 - and no error anywhere
WARNING duplicate order 1 ignored (idempotent retry)

What you see: The first save worked; the duplicate was silently dropped; save(conn, 2, 5) worked. The table has 2 rows and nothing anywhere says that one insert was refused. The improved version names IntegrityError, treats a duplicate as an expected, idempotent retry, and logs a warning. Any other error would still propagate.

In review: swallow everything

Success is reported no matter what happened.

before.pyruns offline
try:
    conn.execute(INSERT, args)
except Exception:
    pass

In review: handle what you expect

A named error is handled and visible; the rest surface.

after.pyruns offline
try:
    conn.execute(INSERT, args)
except IntegrityError:
    log.warning("duplicate %s", id)

The shift: An exception handler should say which failure it understands and what it does about it; everything else is not yours to hide.

Why: Silent failure turns a loud, easy bug into a quiet, expensive one found weeks later.

Land it I tell the author that the handler hides every failure and reports false success, and ask for a specific exception, a deliberate action, and a log line, letting unexpected errors propagate.

Likely follow-ups
"Is catching Exception ever acceptable?"

At the outermost boundary of a unit of work, where you will log the failure and keep going. Inside business logic, almost never.

A request handler, a job runner or a worker loop is where one failure must not take down everything. There I catch Exception, log the full traceback with log.exception, mark the unit of work as failed (return a 500, send the message to a dead-letter store) and continue with the next one. This is the fix for the silent worker (Q142).

The same catch in the middle of a function is harmful because the code below it carries on as if the call had worked, and the real cause is lost.

Two details make the boundary catch safe. First, it never swallows silently: logging with the traceback is the minimum. Second, Exception does not include KeyboardInterrupt and SystemExit, which is the reason I never write a bare except:. In asyncio, CancelledError is also not an Exception, so cancellation still propagates.

"What about contextlib.suppress?"

contextlib.suppress is fine for one specific, harmless exception around one statement. That is the opposite of a broad except: pass.

The standard example is with suppress(FileNotFoundError): os.remove(path). It reads as "delete the file, and if it is already gone, that is fine". It names the exact exception, and the block is one line, so nothing else can be hidden. Compare that with except Exception: pass around a database call, which hides a duplicate key, a lost connection and a typo in the query alike.

Ruff encourages it: rule SIM105 suggests replacing a narrow try, except and pass with suppress.

My checks before using it are three. Is the exception type specific? Is the block a single statement? And is it truly harmless to ignore, for example because the goal state, a missing file, is already reached? If the answer to any is no, I need an explicit handler that logs or acts, and not a suppress.

"How do I convert a low-level error for callers?"

You catch the low-level error and raise a domain error from it, so callers get a meaningful type and the original traceback stays attached.

orders.py
try:
    repo.save(order)
except IntegrityError as exc:
    raise OrderNotSaved(order.id) from exc

The from exc sets __cause__, so the printed traceback shows both: the database error first, then "The above exception was the direct cause of the following exception", then your error. Nothing is lost.

Callers benefit in two ways. They can catch OrderNotSaved without knowing that the repository uses SQLAlchemy, so the storage can change without breaking them. And the message is in business words.

I add the context that helps: the id, the operation. I translate only at a layer boundary, for example the repository turning driver errors into domain errors. Wrapping at every layer produces long chains and no extra information.

"How do I stop this in the codebase?"

I let the tools do the repeating work, so a person does not have to raise the same comment in each review.

Ruff has rules for exactly this pattern. BLE001 flags a blind except Exception, S110 flags a try, except and pass, E722 flags a bare except:, and SIM105 suggests contextlib.suppress for a narrow, harmless case. I turn them on in the project configuration and run Ruff in CI, so a pull request with the pattern fails before a reviewer looks at it.

Some existing code will fail the rules. I add the rule with the current violations listed as exceptions with a comment, and fix them over time, instead of blocking all work. A deliberate broad catch, such as the outer loop of a worker, gets a noqa: BLE001 comment with the reason. That comment is also a signal to the reviewer that someone thought about it.

The conversation then moves to the question a tool cannot answer, which is what the right behaviour is on failure.

Q147 · Scenario. "A config module reads environment variables at import time and breaks the tests. Fix it."

Reveal answer

Strong answer The problem is that importing the module does work. A line such as TAX = float(os.environ["TAX_RATE"]) at module level runs once, the first time anything imports the module. If the variable is missing, the import itself fails, so pytest cannot even collect the tests. If the variable is set, the value is frozen at that moment, and tests that change the environment later see no effect.

The fix is to read configuration in a function or factory, not at import, and to pass the result to code that needs it. A small frozen dataclass Settings with a from_env class method that takes the environment mapping as a parameter is easy to test, because a test hands in its own dictionary and never touches the real environment.

In the application, build the settings once at start-up (get_settings() with lru_cache, or in main) and inject them. In tests, create a Settings directly, or use monkeypatch.setenv and clear the cache. Libraries such as pydantic-settings give this with validation of types and required values.

Picture it The failing import, and the factory version.

config_import_time.py · Python 3.14runs offline
import os, sys, types

src = '''
import os
TAX = float(os.environ["TAX_RATE"])           # runs at import time
'''
mod = types.ModuleType("config_bad")
try:
    exec(src, mod.__dict__)
except KeyError as e:
    print("import config_bad -> KeyError", e, "(collection of the whole test suite dies)")

from dataclasses import dataclass
from functools import lru_cache

@dataclass(frozen=True)
class Settings:
    tax: float
    @classmethod
    def from_env(cls, env=os.environ):
        return cls(tax=float(env.get("TAX_RATE", "0.2")))

@lru_cache
def get_settings():
    return Settings.from_env()

print("default :", get_settings())
print("injected:", Settings.from_env({"TAX_RATE": "0.07"}))

Make the invisible visible: Run it.

output · Python 3.14runs offline
import config_bad -> KeyError 'TAX_RATE' (collection of the whole test suite dies)
default : Settings(tax=0.2)
injected: Settings(tax=0.07)

What you see: Importing the first module raised KeyError: 'TAX_RATE' before any test ran. The factory version returned a default of 0.2 for normal use, and a test passed its own mapping to get 0.07, with no environment variable involved.

Import-time config

Work happens when the module is imported.

config_bad.pyruns offline
# config.py
import os
TAX = float(os.environ["TAX_RATE"])
# every import needs the variable

Config as a function

Work happens when you ask, with an injectable source.

config_good.pyruns offline
# config.py
@dataclass(frozen=True)
class Settings:
    tax: float
    @classmethod
    def from_env(cls, env=os.environ):
        return cls(float(env["TAX_RATE"]))

The shift: Importing should define things, not do things; configuration is a value you create and pass in.

Why: A module that does nothing on import can be imported anywhere (tests, tools, documentation builds) without any set-up.

Land it I keep imports free of side effects, read configuration in a factory that takes the environment as a parameter, build settings once at start-up and inject them, and validate required values with a settings library.

Likely follow-ups
"When is a module-level constant fine?"

For true constants, which never change with the environment. The test: would any test, deployment or user ever want a different value? If yes, it is configuration and does not belong at module level.

Fine at module level: a tuple of supported currencies, a compiled regular expression, and a list of HTTP status codes that mean "retry".

Not fine: anything read from os.environ or a file, anything that opens a connection, and anything that depends on the machine, such as the current time or host name. Those are decisions about the outside world, made at the wrong moment.

A grey area is a value that is a constant today but may become a setting, such as a request timeout. I start with a constant and move it into the Settings class the first time a test or a deployment needs another value. Moving it is a small change if the code reads it from one place.

"What about lru_cache on get_settings in tests?"

The cache returns the first result for the whole life of the process, so a test that changes the environment afterwards still sees the old settings. Here it is:

q147_cache.py outputruns offline
0.2
0.2
0.5

The environment was set to 0.2, read and cached. It was then changed to 0.5, but the second read still shows 0.2. Only after cache_clear() does the third read show 0.5.

In tests, this has two consequences. A test that sets an environment variable with monkeypatch.setenv must also call get_settings.cache_clear(), before and after, otherwise it sees the previous test's settings. This is shared state, as in Q139. In a FastAPI application the cleaner route is a dependency override that returns a different Settings object for the test.

The cleanest answer is to build Settings once in main and pass it in. Then the cache and its clean-up disappear, and each test creates its own object.

"Why not read os.environ directly wherever needed?"

Scattered reads make the list of settings invisible, and each one is a small untested decision. A single Settings class turns them into one visible, validated object.

  1. Visibility: one file lists every setting the program needs, with defaults and types. A new engineer, or an operator writing a deployment, can read it. With scattered os.environ calls they have to search the code.
  2. Validation at start-up: int(os.environ["PORT"]) deep in a request path fails on the first request that uses it, maybe hours after deploy. A Settings class checks everything when the process starts, and the process fails fast with a clear message such as "TAX_RATE is required".
  3. Types once: environment variables are strings. Converting to int, bool or Decimal in one place avoids bugs such as "false" being truthy.

Tests also benefit: they build a Settings object directly and never touch os.environ.

"How do I handle secrets?"

I keep secrets out of code, logs and tests, and I make the type say so.

In production, a secret arrives through the environment or a secret manager (the platform's secrets service, mounted files), not from the repository. The Settings class reads it into a field typed as a secret, for example SecretStr in Pydantic. Printing or logging that object shows **********, and the real value is only available through an explicit get_secret_value() call. That means an accidental log.info(settings) or a traceback with the repr of the object does not leak the password.

Other rules I enforce:

  • no secrets in .env files that are committed, and a secret scanner in CI;
  • tests use fake values, never production ones, so a leak of test logs is harmless;
  • secrets are not copied into image layers at build time, because anyone with the image can read them;
  • keys can be rotated without code changes, because they are read at start-up from outside.

Q148 · Scenario. "A CSV export breaks on names with accents on one platform. Fix it (and say what 3.15's UTF-8 default changes)."

Reveal answer

Strong answer The cause is text encoding. A file contains bytes, and the program must know how to turn text into bytes and back. open(path, "w") without an encoding= argument uses the platform's default, which differs: UTF-8 on most Linux and macOS systems, but a legacy code page such as cp1252 on Windows. The exporter on one machine writes é as the two bytes of UTF-8, the reader on another machine decodes them as cp1252 and shows é. Characters not in the code page raise UnicodeEncodeError.

The fix: always pass encoding="utf-8" when opening text files, and agree on it with the consumer. For CSV files that Excel opens, write utf-8-sig (UTF-8 with a byte-order mark), which makes Excel detect it. Also open CSV files with newline="".

What 3.15 changes (PEP 686): UTF-8 mode is on by default, so the default for open() without encoding becomes UTF-8 on every platform, including Windows. That removes this class of bug for new code and makes behaviour the same everywhere. It does not change files that were written in a legacy encoding, nor other programs' defaults, so explicit encoding= remains the right habit, and it can be switched off with -X utf8=0.

Picture it The mojibake, the mode switch, and what each interpreter reports.

mojibake.py · Python 3.14runs offline
name = "José Müller"
legacy = name.encode("utf-8").decode("cp1252")           # UTF-8 file read with the Windows default
print("UTF-8 bytes read as cp1252:", legacy)
print("cp1252 bytes read as UTF-8:", name.encode("cp1252").decode("utf-8", errors="replace"))
print("fix: always pass encoding=, e.g. open(path, encoding='utf-8-sig') for Excel-made CSVs")
output · Python 3.14runs offline
UTF-8 bytes read as cp1252: José Müller
cp1252 bytes read as UTF-8: Jos� M�ller
fix: always pass encoding=, e.g. open(path, encoding='utf-8-sig') for Excel-made CSVs

What you see: UTF-8 bytes read with the Windows default produced José Müller. The reverse mistake, cp1252 bytes read as UTF-8, produced replacement characters. In both cases the text is damaged, not hidden.

Make the invisible visible: What the interpreters choose as the default text encoding when the C locale is forced.

shell session · Python 3.14 and 3.15.0rc1runs offline
$ LC_ALL=C python3.14 -c "..."
utf8_mode = 1 | default text encoding = utf-8
$ LC_ALL=C python3.14 -X utf8=0 -c "..."
utf8_mode = 0 | default text encoding = ANSI_X3.4-1968
$ LC_ALL=C python3.15 -X utf8=0 -c "..."   # explicit opt-out still possible
utf8_mode = 0 | default text encoding = ANSI_X3.4-1968
$ python3.15 -c "..."   # default
utf8_mode = 1 | default text encoding = utf-8

What you see: With -X utf8=0 the default encoding falls back to the locale's, here ASCII (ANSI_X3.4-1968), and writing é fails. By default both interpreters report UTF-8 on this machine: Linux with a C locale already coerces to UTF-8 on 3.14, so the 3.15 change is felt mostly on Windows and non-UTF-8 locales, which I could not test here.

the fix in coderuns offline
# illustrative
with open(path, "w", newline="", encoding="utf-8-sig") as f:   # Excel-friendly
    csv.writer(f).writerow(["José Müller"])
with open(path, newline="", encoding="utf-8-sig") as f:        # read it back the same way
    rows = list(csv.reader(f))

Why: A text file has no label saying which encoding it uses. The program must say it. Defaults only help when everyone shares them.

Land it I always pass encoding explicitly, use utf-8-sig for CSVs destined for Excel, and I explain that 3.15 makes UTF-8 the default everywhere via PEP 686, which fixes new code but does not relabel existing files or other programs.

Likely follow-ups
"Why does Excel show broken accents for a UTF-8 CSV?"

Because Excel often cannot tell what the encoding of a CSV file is, so it guesses, and it frequently guesses the legacy code page for a file without a marker.

A CSV is a plain text file with no field that says which encoding it uses. Older Excel versions read such files with the system's legacy code page, cp1252 on Western Windows, so the UTF-8 bytes c3 a9 for é are shown as two characters. Our script output showed this exact mix-up:

q148_encoding.py outputruns offline
b'\xc3\xa9' -> é
utf-8-sig starts with: b'\xef\xbb\xbf'

The second line is the byte-order mark that utf-8-sig writes at the start. Excel treats it as the signal that the file is UTF-8. Newer versions of Excel are better at this, but I cannot assume the user's version, so I add the mark.

A format with a defined encoding, such as XLSX, avoids the guess altogether. If the file is for people who use Excel, I either write utf-8-sig or offer an XLSX export.

"How do I find bad legacy files?"

I try a strict UTF-8 decode, and what fails is something else. Then I get the source to tell me its encoding instead of guessing.

Reading a file with open(path, encoding="utf-8") (strict is the default) raises UnicodeDecodeError at the first byte sequence that is not valid UTF-8, and the error shows the byte position. Text written in cp1252 or Latin-1 usually fails quickly, since accented letters become single bytes in the 0x80 to 0xFF range that are not valid UTF-8 on their own. A file that decodes cleanly is almost certainly UTF-8, because random bytes rarely pass.

A library such as charset-normalizer can estimate the encoding, and it is useful to triage a pile of old files. But an estimate is only a guess.

For a data feed, I ask the supplier to state the encoding in the contract and I reject files that violate it, with a clear error naming the byte position.

"What about the standard streams and file names?"

They follow the locale and the operating system, not the open() default, and UTF-8 mode also affects them. In containers I set the encoding explicitly.

  1. Standard streams: sys.stdout, sys.stdin and sys.stderr use an encoding taken from the locale. Printing an accented name into a pipe under the C locale in an old setup can raise UnicodeEncodeError.
  2. File names: Python uses the file system encoding to turn names into bytes. On Linux it is normally UTF-8, but a name with undecodable bytes is handled with a special error handler, so your code can see strange strings.
  3. Containers: minimal images often have no locale. I set LANG=C.UTF-8 or PYTHONUTF8=1 in the Dockerfile.

Setting it there removes a dependency on whichever base image was chosen and makes behaviour the same in tests, CI and production. You can check the actual values with sys.getdefaultencoding(), sys.stdout.encoding and locale.getpreferredencoding().

"Does the new default help or hurt old code?"

Both: it fixes code that was accidentally Windows-only, and it can break code that quietly relied on the old default to read legacy files.

The help: a script that wrote UTF-8 on Linux used to write cp1252 on Windows. Now the same code gives the same bytes everywhere.

The risk: a Windows program that reads files created by an older tool, saved in the system code page, used to work because the default matched. After the change, those files raise UnicodeDecodeError, or silently produce wrong characters if the bytes happen to be valid UTF-8. Such programs must pass encoding="cp1252" explicitly for those files.

To prepare, I search for open( calls without encoding, and run the test suite with -X warn_default_encoding, available since 3.10, which warns at every call that relied on the default. I fix each one by stating the encoding that the file really has.

Q149 · Design. "Port a Java service to Python: what do you keep, and what must change?"

Reveal answer

Strong answer I keep what is about the business and change what is about the language.

Keep: the domain model and rules, the API contract (OpenAPI), the database schema and migrations, the test cases (as data: inputs and expected outputs), the observability names (metrics, log fields), and the deployment shape (container, health checks). Change: dependency injection containers become plain constructor arguments and a small composition root; interfaces become Protocols or simply duck typing; checked exceptions become ordinary exceptions plus clear error types; getters and setters become attributes (properties if needed); builders and Lombok become dataclasses and keyword arguments; equals and hashCode become a frozen dataclass; Streams become comprehensions and generators; null becomes None with | None in the types; Maven or Gradle becomes uv and pyproject.toml; Spring Boot becomes FastAPI or Django; threads and a pool become asyncio or processes, with the GIL in mind. Plan to watch: concurrency (a Java thread pool does not translate to threads in Python for CPU work, Q93), performance of hot loops, no compile-time safety unless you add a type checker and Pydantic, and packaging and deployment differences. I port one vertical slice first, running both services side by side with the same contract tests, and move traffic gradually.

Picture it The same small service class in both languages, to show the shape of the change.

Java · Spring

Constructor injection through the container, a checked exception, a getter-based value object.

PriceService.javaruns offline
@Service
public class PriceService {
  private final RateClient rates;
  public PriceService(RateClient r) {
    this.rates = r;
  }
  public Money price(Order o)
      throws RateException {
    return o.total()
      .times(rates.rate(o.cur()));
  }
}

Python

Plain constructor argument, a Protocol for the client, a frozen dataclass for money, no container.

price_service.pyruns offline
class RateClient(Protocol):
    def rate(self, cur: str) -> Decimal: ...

class PriceService:
    def __init__(self, rates: RateClient):
        self.rates = rates

    def price(self, o: Order) -> Money:
        return o.total() * self.rates.rate(o.cur)

The shift: Most of the Java ceremony (container, interfaces, getters, checked exceptions) exists to compensate for static rigidity; in Python you keep the design and drop the scaffolding.

Keep, change, and watch when porting.
AreaJava habitIn Python
WiringSpring container, annotationsconstructor arguments, composition root in main
ContractsinterfacesProtocol (Q117)
ValuesLombok, equals/hashCode@dataclass(frozen=True, slots=True)
Errorschecked exceptionsexceptions with domain types; handle at boundaries (Q146)
CollectionsStreamscomprehensions, generators (Q58)
Concurrencythread pools, virtual threadsasyncio, processes, or free-threaded build (Q91, Q93)
BuildMaven / Gradleuv, pyproject.toml, lock file (Q128)
Safety netcompilertype checker + Pydantic + tests (Q123)

Why: The port is easiest where the design was clean: small classes with explicit dependencies translate almost line for line. Where the Java relied on framework magic, you must replace the behaviour deliberately.

Land it I keep the domain, contract, schema and tests, drop the container and ceremony in favour of plain composition, Protocols and dataclasses, re-think concurrency for the GIL, add types and validation as the compiler replacement, and migrate one slice at a time against shared contract tests.

Likely follow-ups
"What is the biggest trap?"

The biggest trap is writing Java in Python, and the second is copying a concurrency design that does not fit the interpreter.

Transliteration produces code that runs but is heavy: a getter and setter for every field, a factory class for each object, an interface with a single implementation for every dependency, a Builder where keyword arguments would do. Python programmers find it slow to read and write, and the extra layers add bugs without adding safety. The cure is the idioms from this chapter: dataclasses, plain functions and Protocols only where several implementations really exist.

The concurrency trap is a fixed thread pool sized for CPU work. In Java the threads run on several cores. In CPython with the GIL, the same design does not speed up CPU-bound code (Q93), and you find that out under load. The port should choose asyncio for I/O, a process pool for CPU, or a free-threaded build after checking the dependencies.

"How do you prove the port is correct?"

By comparing behaviour between the two services on real traffic, before anyone depends on the new one.

  1. Replay: record production requests, with sensitive data removed, and send the same requests to both services. Compare status codes, bodies and headers.
  2. Shared contract tests: run the same suite, written against the HTTP contract, against both. A test that passes on only one of them shows a gap.
  3. Shadow mode: the new service receives a copy of live traffic and its answers are thrown away, with differences logged. It runs for weeks, so rare cases appear.

The usual findings are boring and important. Rounding of money (Java BigDecimal against Python Decimal modes), null against missing fields in JSON, date and time zone formats, sorting of strings with accents, and default page sizes. Those are the differences between two correct programs and the main risk of a port.

When differences reach zero or an agreed list, I move traffic gradually: 1%, 10%, 50%, 100%.

"Should I port at all?"

Only for a reason that outweighs a rewrite's risk. A port is a rewrite, and rewrites are famous for taking longer and introducing bugs that the old code had already fixed.

Good reasons: the team that will run the service writes Python and cannot maintain Java; the service sits next to an ecosystem that is strong in Python, such as data science or machine learning; or iteration speed matters more than raw performance, as in a service that changes weekly. Weak reasons: a preference, or a belief that Python is simpler.

A stable, CPU-heavy Java service that nobody is touching is the case I would leave alone. If a new capability is needed beside it, I build the new part in Python as a separate service with a clear contract, instead of porting the old one.

"What about performance expectations?"

For I/O-bound services the difference is modest, and it depends more on the concurrency design than on the language. For CPU-bound hot paths, Python will be slower, and I plan for that.

A typical service spends most of its time waiting for the database and other services. There, an asyncio design with a connection pool can serve similar traffic to a Java thread pool, and the database is the limit in both cases.

For code that computes, such as pricing rules in a tight loop, expect a large gap (often many times slower) unless the work moves to a faster layer. The options are numpy or another vectorised library, a native extension, a process pool, or leaving that component in Java behind a service boundary.

I do not promise a number before measuring. I profile the Java service for its hot paths, write a thin Python version of one of them, and time that against realistic data. The result decides which parts are ported and which stay.

Q150 · Design. "You are the senior on a Python team. Write your top-ten code-review checklist and defend each item."

Reveal answer

Strong answer Each item below is a bug class I have seen cause an incident, with a reason in one sentence. The links go to the idiom that fixes it.

Top-ten Python review checklist.
#CheckWhy it mattersIdiom
1No mutable default arguments or shared module-level statedefaults are created once; requests leak into each otherNone default
2No broad except that hides failures; resources use withsilent failures and leaked connections are found weeks latercontext manager
3No blocking calls inside async defone call stalls every request on the loopto_thread
4Tasks are owned: TaskGroup or saved references; cancellation re-raisedtasks vanish, errors are lost, shutdown hangsTaskGroup
5Types at public boundaries, no new Any, validated inputthe checker only protects what it can seeProtocol
6Money is Decimal or cents; times are timezone-aware UTCfloat and naive time give wrong answers that look rightfrozen value
7No O(n) lookups in loops; performance claims come with a measurementlist-in-loop and guesses cause the slow endpointprofile first
8Decorators use wraps; closures in loops bind values; caches are boundedlost names, last-value bugs and memory leakswraps
9Tests are independent, patch where used, fast, and assert outcomesorder-dependent and mock-heavy suites hide bugspatch where used
10Dependencies locked; config injected, not read at importa deploy must equal what was testedlockfile

I defend the order: the first three are about silent wrong behaviour, which is the most expensive kind. Items 4 and 5 are about structure. Items 6 to 10 are about correctness, speed and delivery. I would also add the rule that matters most socially: comment on the risk, not the style, and let the formatter and linter settle the rest.

Picture it One review comment, written the way I would leave it, with the evidence from this chapter.

review comment on a pull requestruns offline
# illustrative
File: pricer/notify.py   line 41
  try:
      db.save(order)
  except Exception:
      pass

Blocking: this reports success even if the insert failed (see the duplicate-order
demo, Q146: 2 rows saved, no error anywhere). Please catch the specific error
(IntegrityError for an idempotent retry), log it, and let anything else raise.
Non-blocking: a test for the duplicate case would pin this.

Make the invisible visible: A review is faster when most of the list is automated. Which items a tool can enforce.

What can be automated.
CheckTool
1, 2, 3, 8 (patterns)Ruff rules (B006 mutable default, BLE001 blind except, ASYNC rules, B023 loop closures)
5 (types)mypy or pyright in strict mode on typed packages
10 (locks, config)uv sync --locked in CI; a test that imports every module with an empty environment
9 (tests)random test order, coverage floor, time limit per test
4, 6, 7review and tests; partly Ruff, partly human judgement

Why: Automate the mechanical items so that human review time goes to design, risk and the things a tool cannot see.

Land it I review for silent failure first, then concurrency structure, types and correctness, then speed and delivery, I tie every comment to a bug I can demonstrate, and I automate the mechanical rules so review time goes to risk.

Likely follow-ups
"Why mutable defaults first?"

It is first because it is the most common source of "works in tests, breaks in production under load", and because it hides: the bug is in one line and appears far away as data belonging to another user.

A default argument such as codes=[] is created once, when def runs, and every call without the argument shares that one list. In a test with one request at a time, it can seem to work. In production, request B appends to the list that request A used, and customer B receives customer A's discount code. That is the Black Friday incident from the start of the chapter.

The fix is a single line: default to None and create the list inside the function (pat-none-default).

Because it is so mechanical, I do not rely on a human to spot it: Ruff's B006 catches mutable defaults, so a reviewer's attention goes to the harder items.

"How strict should a review be on typing?"

Strict at boundaries and relaxed inside. A type is a promise to other code, so it matters most where other code meets yours.

I require full hints on public functions, on classes and on anything imported by another module, plus validated input where data enters from outside (Pydantic or a similar parser). A wrong type travels far before it fails there.

Inside a module, I relax. A three-line private helper with an obvious local variable does not need a hint, and I will not block a pull request over it: inference does the job, and the author has the reason to know better than I do.

Two things I ask for in review. A new Any or cast or type: ignore needs a short comment saying why, because each one turns checking off for the code it touches.

The rule behind it: types are worth what they protect. Spend review attention where a mistake is expensive.

"How do you handle disagreement about style?"

By moving style out of the discussion. A formatter ends it, and reviews are kept for behaviour, risk and clarity.

Ruff's formatter and linter make one decision for the whole team, so quote marks, line length and import order are not comments in a review. If someone dislikes a rule, they propose a configuration change in its own pull request.

For genuine design disagreements, such as one class or two, a function or a method, I ask for the reasoning. Then I apply a simple test: does either design risk a bug, make the code hard to change, or confuse the next reader? If both are sound, I accept the author's choice, since the author will maintain it and a reasonable alternative is not a defect.

I label comments as non-blocking suggestions or blockers, so the author knows which is which.

"What would you add to the list for your own team?"

The incident history. Each production incident should leave one line on the checklist and, where possible, one automated rule, so that the same bug class cannot return.

The ten items here came from failures. When a new one occurs, for example a timeout missing on an external call that froze a worker (Q142), the post-incident review asks two questions. Could a checklist item have caught it? Could a tool catch it without a human, such as a Ruff rule, a type check, a test or a startup check? The answer to the second goes into CI. The answer to the first becomes a line, with the bug it stands for.

The list stays short because tools take items over. Mutable defaults are already caught by B006, so the item can shrink to a reminder. Items that need judgement stay for people.

A checklist that grows from real failures stays relevant and short enough to remember, and the team trusts it because each line has a story behind it.

12 · RecapWhat You Can Do Now

  • You can explain names, objects and memory: why codes=[] leaks between calls, how reference counting and the cycle collector free memory, and when to copy deliberately or use a frozen value
  • You can say how len, for, with, + and .attr really work, including the attribute-lookup order, descriptors, slots, the MRO and the order of class creation
  • You can explain functions as objects: late-binding closures, decorators with and without arguments, generators as suspended frames, and a bounded cache
  • You can describe how CPython runs code: bytecode, the specialising interpreter, the GIL and what it does not protect, free-threading, and the import system including lazy imports
  • You can choose a concurrency model from what the work waits on, and use asyncio safely: no blocking calls, TaskGroup, kept task references, honoured cancellation, bounded concurrency
  • You can type a codebase gradually, with Protocols, generics and ParamSpec, and say what a checker cannot see; and package it with a venv, pyproject.toml, a lock file and wheels
  • You can test with fixtures, patch where a name is used, write property tests, and run async tests, and handle money, time, encodings, configuration and logging the production-safe way
  • You can find where time goes with a profiler before changing anything, and answer "Python is slow" with measured numbers and an ordered list of options
🧠 Flex your memory

Close the page and write down, from memory, the order in which Python resolves obj.attr: data descriptor, instance dictionary, non-data descriptor or class attribute, __getattr__. Then explain why counter += 1 from four threads lost updates on the free-threaded build but not on the regular one, and why a Lock fixes both. Finally reach back to Chapter E2: compare the JVM's tracing garbage collector with CPython's reference counting plus a cycle collector, and say which one frees an object the moment its last reference goes away.

13 · SummaryAll 30 Idioms on One Page

Every idiom in this chapter, each with the problem it solves and the solution in one line. Click an idiom name to jump to its full breakdown.

02 · Names, objects and memory

4 idioms.
IdiomProblemSolution
None defaultA mutable default such as codes=[] is created once and shared by every call.Default to None (or a private sentinel) and create the new object inside the function.
Copy deliberately, or make it immutableA shallow .copy() of nested config shares the inner objects, so one tenant's edit reaches all.Deep-copy at the boundary, or make the config immutable so nobody can edit it.
A cache that does not keep objects aliveA cache keyed by object holds a strong reference, so entries never die.Use WeakValueDictionary so an entry disappears when the object does.
The frozen value objectMoney and similar values are changed by accident and cannot be dict keys.@dataclass(frozen=True, slots=True) with Decimal: immutable, hashable, compact.

03 · The data model

5 idioms.
IdiomProblemSolution
Keep __eq__ and __hash__ consistentDefining __eq__ alone makes the class unhashable, or equal objects get different hashes.Equal objects must hash equally; hash only immutable fields, or use a frozen dataclass.
Put cleanup in a context managerA close() after an exception is skipped, leaking files and connections.Use with, written as a class or with contextlib.contextmanager; ExitStack for many.
A reusable validated field as a descriptorThe same validation is copied across many classes.Write one descriptor class with __set_name__ and reuse it as a class attribute.
Slots for millions of small recordsEach instance carries a dictionary, so memory explodes.Declare __slots__ (or slots=True) for a fixed layout; accept no new attributes.
A plugin registry with __init_subclass__Plugins must be registered by hand and someone forgets.Register every subclass in __init_subclass__ of the base; no metaclass needed.

04 · Functions, closures, decorators and generators

5 idioms.
IdiomProblemSolution
Always use functools.wrapsA decorator replaces the function's name and docstring with the wrapper's.Apply @functools.wraps(fn) to the wrapper.
A decorator with arguments is three layers@retry(times=3) does not work with a two-layer decorator.Outer function takes the arguments, returns the decorator, which returns the wrapper.
Bind the value when you create the closureLambdas created in a loop all see the last loop value.Bind by default argument (t=tenant) or functools.partial.
Process big data as a generator pipelineReading a whole file into a list exhausts memory.Chain generators (parse, filter, aggregate) so one item flows at a time.
Bound your caches, and never cache a method on selfAn unbounded cache grows forever and a cached method keeps self alive.Set maxsize, cache module-level functions, or use cached_property.

05 · How CPython runs your code

4 idioms.
IdiomProblemSolution
Guard process creation with __main__Spawned workers re-import the main module and start more workers.Put start-up code under if __name__ == "__main__":.
Break import cycles, do not work around themTwo modules importing each other fail with a partially initialised module.Move shared code to a third module, import the module not the name, or import inside the function.
Lazy imports (3.15, PEP 810)Heavy imports slow start-up of a command-line tool.lazy import x at module level defers loading until first use.
Vectorise the hot loopA numeric Python loop runs at interpreter speed.Push the loop into compiled code: numpy, builtins like sum, or native extensions.

06 · Concurrency

6 idioms.
IdiomProblemSolution
Move blocking calls out with to_threadA blocking call inside async def freezes every request.Run it with await asyncio.to_thread(...) or an executor.
Run related tasks in a TaskGroupWith gather, a failure leaves sibling tasks running.Use asyncio.TaskGroup: siblings are cancelled and errors come back as an exception group.
Bound concurrency with a SemaphoreHundreds of simultaneous outbound calls overload the downstream service.Wrap the call in async with asyncio.Semaphore(n).
Process pool with big units of workTiny tasks cost more to pickle and send than to run.Chunk the work, send small arguments, and use one worker per core.
Carry request context with contextvarsThread-local values are overwritten when tasks share a thread.Use ContextVar: each task gets its own copy.
Keep a reference to every fire-and-forget taskThe loop holds tasks weakly, so an unreferenced task can be destroyed.Hold tasks in a set with a done-callback, or run them in a TaskGroup.

07 · Types, packaging, testing and performance

6 idioms.
IdiomProblemSolution
Describe behaviour with a ProtocolAn ABC forces inheritance, so third-party classes and fakes do not fit.Declare a Protocol: any class with the right methods is accepted.
Keep signatures with ParamSpecAn untyped decorator erases the signature of everything it wraps.Type it with ParamSpec and a return TypeVar (and Concatenate to add arguments).
Patch the name where it is usedPatching the definition has no effect after from x import y.Patch module_under_test.y, or pass the dependency in.
Build test data with fixtures, not shared globalsShared module-level state makes tests order-dependent.Use function-scoped fixtures with yield teardown.
Lock every dependency, and install from the lockA transitive dependency upgrades itself between test and deploy.Commit uv.lock and install with uv sync --frozen.
Profile first, then change one thingOptimising by guess fixes the wrong code.Measure with a profiler, fix the hot spot, and measure again.