Python Deep Dive — Internals + 150-Question Drill
"Python is easy to write and hard to explain. The senior round asks you to explain it."
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.
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__)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.
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)")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.
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.
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.
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)--- 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_VALUEThe 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.
- 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.
- The data model (section 03):
len(x),for,with,+andx.attrare all calls to special methods on the type. Learn those methods and operators, iteration, context managers and descriptors stop being magic. - Functions are objects (section 04): functions carry attributes and captured variables, which is why closures, decorators and generators behave as they do.
- 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.
- Concurrency models (section 06): threads, processes, asyncio, subinterpreters and free-threaded threads each share different things and fail in different ways.
- 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 | Idiom |
|---|---|---|
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.
// illustrative
public record Money(
BigDecimal amount,
String currency) { }
// equals, hashCode, toString
// are generated, fields finalPython
A frozen dataclass does the same job. The decorator writes the methods, and frozen=True blocks assignment.
@dataclass(frozen=True)
class Money:
amount: Decimal
currency: strThe 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.
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)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.
| Version | Headline changes | Why it matters | Taught 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.
- The problem: what goes wrong without it, shown on pricer.
- How it works: the mechanism in two to four numbered steps.
- Without and with: a real run of the broken version, then a real run of the fixed version.
- Works / Fails: where the idiom helps and where it does not.
- 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.
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)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 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.
# 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))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' ): FalseThe 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.
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)))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): -3550055125485641917Three 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.
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)<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: TrueA 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.
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)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.
// 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.
def add_one(xs):
xs.append(1) # caller sees it
def replace(xs):
xs = [1] # caller does notThe 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.
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]))before any call: ([],)
after call 1 : (['FIRST50'],)
after call 2 : (['FIRST50', 'WELCOME'],)
id of default list stays: TrueWatch __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.
- Declare:
def apply_codes(order, codes=None). The only thing stored in__defaults__isNone. - Check:
if codes is None: codes = []. This line runs on every call, so each call builds its own list. - When None is a real answer: make a private sentinel,
_MISSING = object(), and compare withis. No caller can pass it by accident.
First, the version without the idiom, as already run in section 01:
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.
_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__)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.
- Works: every function that accepts an optional list, dict or set, and every dataclass field (where
field(default_factory=list)plays the same role). - Fails: if you test with
if not codes:instead ofif codes is None:. A caller who passes their own empty list then gets silently replaced by a new one and loses the reference they expected to fill.
- Interview takeaway: "Defaults are evaluated once, when
defruns, and stored in__defaults__, so I never default to a mutable object; I default toNoneand build the list inside."
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.
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"])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: TrueThe 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.
- Find the boundary: the point where shared data becomes one tenant's data, here the function that builds a tenant's config.
- Copy there, deeply:
copy.deepcopy(BASE)once per tenant, at start-up, not on every request. - Prefer immutable inner values: a tuple of fees instead of a list means that even a shallow copy cannot be corrupted by an append.
- For a read-only shared object: wrap it in
MappingProxyType, or in afrozendicton 3.15, and share it freely.
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")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 dictTenant 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.
- Works: configuration, defaults, templates, anything built once and handed to many owners.
- Fails: deep-copying a huge structure per request (slow), and deep-copying objects that hold sockets, locks or open files (they cannot be copied meaningfully).
- Interview takeaway: "
.copy()copies one level, so I copy deeply once at the ownership boundary, and I keep shared data in immutable types so the question never comes up."
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.
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")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
doneWith 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.
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())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)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.
# illustrative: choose and watch a GC
java -XX:+UseG1GC -Xmx2g \
-Xlog:gc -jar pricer.jar
# objects die when a collection
# finds them unreachablePython
Counts free most objects instantly. A small collector handles only cycles, and you can call it by hand.
import gc
print(gc.get_threshold())
# plain objects die at refcount 0
gc.collect() # frees only cyclesThe 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.
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")sys.getsizeof(words) : 8856 bytes (just the list's pointer array)
one string : 57 bytes
sum of getsizeof(each) : 65856 bytes
tracemalloc total : 66264 bytesA 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.
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: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 BRead 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.
- Create the cache:
cache = weakref.WeakValueDictionary(). - Store values:
cache[key] = obj. The cache does not ownobj; the caller does. - Read with
.get: an entry may have disappeared since you last looked, so always handleNone.
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"))both alive : strong 1 weak 1
after callers drop : strong 1 weak 0
weak cache lookup : NoneThe 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.
- Works: caches of objects that are alive for a reason of their own, such as parsed documents or session objects, where you only want to share an existing object.
- Fails: for caches of values nobody else holds. Those entries disappear immediately, so you get no caching. Built-in
int,strandtuplevalues cannot be weakly referenced at all. For "keep the last N results" use a bounded cache from section 04.
- Interview takeaway: "A dict cache is a strong owner and leaks by design; when the cache should not decide an object's lifetime I use a
WeakValueDictionary, and I find real leaks by diffingtracemallocsnapshots."
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.
- Declare the fields with types:
amount: Decimal,currency: str. - Freeze it:
frozen=Truemakes__setattr__raiseFrozenInstanceError, and makes the generated__hash__use the fields. - Return new values: an operation such as
+builds and returns a newMoney; 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.
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"))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.3Assigning 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.
- Works: money, ids, coordinates, config values, keys, anything compared by value.
- Fails:
frozenis shallow. A frozen dataclass holding a list lets you mutate that list, and its hash then raisesTypeErrorbecause lists cannot be hashed. Keep fields immutable too (tuples,Decimal, strings).
- Interview takeaway: "Values are immutable: a frozen, slotted dataclass over
Decimalgives me equality, hashing and no way to corrupt a price after creation."
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.
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)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.
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(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()) = TrueCalling 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.
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]))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.
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)Rs 1,234.50 | Money('1234.5') | [Money('1234.5')]
eval(repr(m)).amount == 1234.5The 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.
- Decide what identity means: for a rule, the code and the percentage.
- Hash only immutable fields:
hash((self.code, self.pct)), using the same fields as__eq__. - 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:
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)))rule in set after edit: False | set size: 1
frozen dataclass lookup: True
eq implies equal hash : TrueThe 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.
// 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.
@dataclass(frozen=True)
class Rule:
code: str
pct: int
# __eq__ and __hash__ generated,
# fields cannot change afterwardsThe 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.
- Works: value objects, rules, keys, and anything stored in a set or used as a dict key.
- Fails: mutable entities such as a database-backed
Orderwhose fields change. Leave those unhashable, or hash only a stable id. Also,eq=Truewithfrozen=Falsein a dataclass keeps the class unhashable on purpose.
- Interview takeaway: "Equal objects must hash equally and the hash can only use fields that never change, so I use a frozen dataclass; Python sets
__hash__toNoneas soon as you define__eq__alone."
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.
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)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 30The 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.
- Enter: call
thing.__enter__(); whatever it returns becomesx. - Run the body inside a
try. - Exit: always call
thing.__exit__(exc_type, exc, tb), with threeNones if the body succeeded, or the exception's details if it failed. - Decide: if
__exit__returns a true value the exception is swallowed; otherwise it continues up the stack.
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")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 r1Case 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.
- Write it once: a
@contextmanagergenerator withtry: yield ... finally: release. - Use it everywhere:
with connection(): ...; the call site cannot forget the release. - For many resources:
ExitStack, instead of nestingwithblocks.
Without the idiom, pricer's batch function releases its pooled connection on the last line. Three batches run; the second has a bad order:
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) acquired, open = 1
released, open = 0
acquired, open = 1
caught: bad order
acquired, open = 2
released, open = 1
connections still open: 1The 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:
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) acquired, open = 1
released, open = 0
acquired, open = 1
released, open = 0
caught: bad order
acquired, open = 1
released, open = 0
connections still open: 0Every "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.
// illustrative
try (Connection c = pool.get()) {
reprice(c, orders);
} // c.close() always runsPython
A with block calls __exit__ in the same situations, and the manager can be a generator.
def reprice_batch(orders):
with connection():
for o in orders:
check(o)
# release runs in finallyThe 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.
- Works: files, locks, database transactions, temporary directories, timers, and anything that must be undone.
- Fails: if
__exit__returnsTruecarelessly, errors vanish. And in an@contextmanagerwithout atry/finally, the code afteryieldis skipped when the body raises, just as in the broken example.
- Interview takeaway: "
withcalls__enter__, runs the body in atry, and always calls__exit__; I wrap every acquire and release pair in a context manager, with the release infinally."
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.
obj.attr is resolved. A data descriptor on the class beats the instance dictionary; the instance dictionary beats methods and other non-data descriptors.- 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. - Instance dictionary: otherwise, if the name is in
obj.__dict__, that value is returned. - 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. - The
__getattr__hook: if everything failed and the class defines__getattr__, it is called with the name; otherwiseAttributeError.
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.
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) 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 -> fallbackThe 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__.
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))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? TrueAll 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.
- Learn the name:
__set_name__stores the field's name so the descriptor knows where to keep the value (here_priceon the instance). - Check on write:
__set__validates and stores. Every assignment, including the one in__init__, goes through it. - Return itself on class access: if
objisNonethe attribute was read on the class, and returningselflets tools inspect the field.
Without the idiom, two fields in one class:
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)rejected: price must be positive, got -5That is 12 lines for two fields, and the code must be pasted into every other class that has a numeric field. With the idiom:
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__)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.
- Works: the same validation or conversion across many classes, lazy computed values, and anything that must run on every read or write of an attribute.
- Fails: descriptors keep per-instance data on the instance, never on the descriptor itself, which is shared by every instance (a classic bug stores
self.valueon the descriptor and every object sees the same number). For one field in one class, plain@propertyis simpler.
- Interview takeaway: "A descriptor is an object with
__get__and maybe__set__living on the class; data descriptors beat the instance dict, which is why a validated field written once works in 20 classes."
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.
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__"))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 FalseOne 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.
- Measure first: use
tracemallocon a realistic count, as in the run above. If the saving is small, skip it. - Add slots:
@dataclass(slots=True), or__slots__in a plain class. - 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.
- Works: large collections of small, fixed-shape records, and immutable value objects (combined with
frozen=True, as inpat-frozen-value). - Fails: classes with few instances (nothing to save), classes that need dynamic attributes, and code that relies on
vars(obj).
- Interview takeaway: "Slots drop the per-instance dictionary; I measured about 1.6 times less memory for a million objects and no speed change, so I use them for big collections of small records and nowhere else."
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.
Rule appears once, after both Taxed and Discounted.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)['Promo', 'Taxed', 'Discounted', 'Rule', 'object']
Promo.__init__
Taxed.__init__
Discounted.__init__
Rule.__init__
tax 8 pct 10The 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.
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.
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)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.
- Declare:
class First50(Rule, code="FIRST50")passescodeas a class keyword argument. - Register:
Rule.__init_subclass__(cls, code=...)storesRule.registry[code] = cls. - Reject mistakes at definition time: a subclass that forgets
coderaisesTypeErrorwhile the module is imported, not in production.
Without the idiom, registration is a manual line that one developer forgot:
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")FIRST50 -> First50
FLAT20 -> KeyError: never registeredThe unregistered rule is found only at lookup time, in production. With the idiom:
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)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.
- Works: plugins, handlers keyed by name or type, serialisers, and any "every subclass must be known" rule. It only needs the module of each subclass to be imported.
- Fails: if a plugin lives in a module nobody imports, it never registers (so import the plugin package at start-up). A global registry can also leak classes between tests.
- Interview takeaway: "
__init_subclass__runs on every new subclass, so a registry fills itself and bad subclasses fail at import; I reach for a metaclass only when I must change how the class is built."
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.
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)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.
| Option | Pick it when | Cost 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.NamedTuple | A 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 BaseModel | Data 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.
# 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)repricing crisp
repricing crisp
repricing crisp
loop variable after the loop: crispWhy: 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.
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))<class 'function'> price | Price one line.
params : ('qty', 'unit')
defaults : (2.5,) {'tax': 0.2}
attribute : 1
flat 30.0
bulk 24.0Three 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.
- Local: names the function itself creates, which means its parameters and anything it assigns to.
- Enclosing: names in any function this one is nested inside, working outwards.
- Global: names at the top level of the module (the file).
- Built-in: names Python provides everywhere, such as
len,printandValueError.
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.
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)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_VALUEWhy: 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.
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")total: 101 seen: 2
builtins <- built-ins live in the last ringA 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.
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)cell objects: ['0x75f5cfe95de0', '0x75f5cfe95de0', '0x75f5cfe95de0']
one cell shared: True
cell_contents: crisp
free variable names: ('tenant',)
counter cell after 2 calls: 2The 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.
Java · Spring
A Java lambda may only capture a variable that never changes. The compiler enforces it, so the surprise cannot happen.
for (String tenant : tenants) {
handlers.add(() -> reprice(tenant));
}
// each pass has its own `tenant`, and it is
// effectively final: changing it is a
// compile errorPython
A Python closure captures the variable itself, and one loop variable is reused on every pass.
for tenant in tenants:
handlers.append(lambda: reprice(tenant))
# ❌ TRAP: one variable for the whole loop,
# read when the lambda is CALLEDThe 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.
- 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. - functools.partial:
partial(reprice, tenant)builds a callable that stores the argument inside itself. No lambda, no cell. - Factory function: a small
make_handler(tenant)whose parameter is a fresh variable on every call, so each returned lambda has its own cell.
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])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.
| Option | Pick it when | Cost or catch |
|---|---|---|
Default argument t=tenant | A 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.partial | You 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 function | The 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. |
- Works: every handler repricing its own tenant, and the same shape works for thread targets,
sorted(key=...)built in a loop and button callbacks. - Fails: binding by default argument for a value that must be seen changing later. If you actually want a closure to follow a variable (a counter, a config reloaded at run time), keep the cell and use
nonlocal. - Interview takeaway: "A Python closure captures the variable, not the value, so a lambda made in a loop sees the last value. I bind the value at creation with
partial, a default argument or a factory."
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.
# illustrative
@announce
def quote(order_id): ...
# is exactly:
def quote(order_id): ...
quote = announce(quote) # runs ONCE, when the def statement runsThe 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.
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))decorating quote (at definition time)
--- module body finished, nothing called yet ---
calling quote
quote for o-1
name: wrapper | doc: None | wrapped: NoneLook 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.
@Transactional
public Quote quote(String id) {
return repo.find(id);
}
// the method body is untouched; Spring
// builds a proxy around the bean laterPython
A decorator is ordinary code. It runs at import time and replaces the function with whatever it returns.
@transactional
def quote(order_id):
return repo.find(order_id)
# quote is now whatever transactional(quote)
# returned: a different function objectThe 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.
- Write the wrapper: use
*args, **kwargsso it accepts any call. - Decorate the wrapper: put
@functools.wraps(fn)directly abovedef wrapper. - Return the wrapper: the caller gets a function that still looks like the original.
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__)wrapper doc=None sig=(*args, **kwargs)
b doc='Price an order.' sig=(order_id: str, qty: int = 1)
b.__wrapped__ is the original: bThe 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.
- Works: Flask and FastAPI routing by function name, log lines that name the real function,
help(), andpytestintrospection. - Fails:
wrapscopies identity, not behaviour. A wrapper that changes the arguments or the return type still lies about its signature; for that, see the typed-decorator idiom in section 07. - Interview takeaway: "A decorator replaces the function, so I add
functools.wrapsto keep the name, docstring and__wrapped__. Without it, anything that reads function metadata breaks."
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.
- Outer: takes the settings (
times,backoff) and returns the decorator. - Middle: takes the function being decorated and returns the wrapper. This is the plain decorator from before.
- 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.
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) 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 downThe 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.
- Works: retries, timeouts, caching with a TTL, permission checks with a required role, rate limiting; any wrapper that needs settings.
- Fails: forgetting the parentheses.
@retryalone passes your function astimesand breaks at the first call. Also, never retry a call that is not safe to repeat (a payment) unless it is idempotent, as discussed in Chapter E17. - Interview takeaway: "
@retry(times=3)is a call that returns a decorator, so I write three layers: settings, function, wrapper. I retry only named exceptions, back off exponentially and re-raise the last error."
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.
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()apply cache
apply auth
--- definition done ---
enter auth
enter cache
body
exit cache
exit authRead 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.
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__)price 2 CountCallsfunctools.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.
| Option | Pick it when | Cost or catch |
|---|---|---|
Function decorator with wraps | Almost 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 helper | You 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.
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))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_CLOSEDRead 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.
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: pass10 15
got ValueError inside the generator
throw -> -1
cleanup (finally runs on close)
GEN_CLOSED
a
inner got X
outer got inner-resultThe 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.
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.
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 upThe 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.
- Parse: a generator turns each text line into a small tuple.
- Filter: a generator passes on only the rows you care about.
- Aggregate: an ordinary function (not a generator) loops over the last stage and builds the small result.
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.
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")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.
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 differThe 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.
- Works: log files, CSV exports, database cursors, paginated APIs, any "read, transform, filter, aggregate" job where the result is much smaller than the input.
- Fails: when you need the data twice (a generator is used up after one pass), need random access or the length up front, or must sort everything (sorting needs all rows in memory; use an external sort or a database).
- Interview takeaway: "I chain generators so each item flows through every stage before the next is read; memory is one item instead of the file. I measured 303.6 MB against 0.2 MB on a 156 MB log."
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.
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")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 differThe 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.
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)")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.
cache/lru_cache: remember a function's results by its arguments. Use it for a pure lookup such as an exchange rate or a parsed config.lru_cache(maxsize=N)keeps only the N most recently used results;cacheis the same with no limit.cached_property: compute an attribute once per object, then store it in the instance's own dictionary. Use it for a heavy value that belongs to one object.partial: fix some arguments of a function in advance. Use it to bind a value into a callback, as in the closure idiom above.singledispatch: pick an implementation by the type of the first argument. Use it for arender()orserialise()function that differs per type without a chain ofisinstance.reduce: fold a sequence into one value with a two-argument function. Use it sparingly; a plain loop is usually clearer.
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__) 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: TrueWalk 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.
- Cache a module-level function: take the data as arguments (
rate_for("EUR")), not the object. - Make the cache per instance: build
lru_cacheinside__init__so it lives and dies with the object. - 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.
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)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 1Why: 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".
| Option | Pick it when | Cost or catch |
|---|---|---|
@cache on a module-level function | The 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 function | Arguments 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_property | One 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. |
- Works: memoising pure functions of plain arguments with a chosen bound, and checking
cache_info()in a metrics endpoint. - Fails: caching a function that depends on something other than its arguments (the clock, a database row that changes). The cache will happily return stale answers forever.
- Interview takeaway: "
lru_cacheon a method keepsselfalive through the cache key. I cache a function of plain data, bound it withmaxsizechosen fromcache_info(), or usecached_property."
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.
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.
$ 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| Interpreter | 1 thread | 4 threads | What happened |
|---|---|---|---|
| Python 3.14 (GIL on) | 0.70 | 1.04 | 4 threads were about 49% slower than 1 |
| Python 3.14t (GIL off) | 0.84 | 0.25 | 4 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.
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 differSo 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.
- Tokens: the text is cut into words and symbols (
total,=,price,*,qty). - 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.
- 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).
- Eval loop: a big C loop reads each instruction and does what it says. Every Python line you run is going through this loop.
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.
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(" "))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 00Read 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.
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:")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.
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)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] lastiThe 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.
- 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.
- 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.
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.
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")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 differThe 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.
import dis
counter = 0
def bump():
global counter
counter += 1
dis.dis(bump) 3 RESUME 0
5 LOAD_GLOBAL 0 (counter)
LOAD_SMALL_INT 1
BINARY_OP 13 (+=)
STORE_GLOBAL 0 (counter)
LOAD_CONST 1 (None)
RETURN_VALUEFour 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.
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:,}")$ 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,784On 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.
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):,}")Python 3.14.7 GIL enabled: True expected = 80,000
unsafe : 20,005
locked : 80,000Even 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.
$ 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 : 1What 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).
| Option | Pick it when | Cost or catch |
|---|---|---|
| Threads on free-threaded 3.14t | Shared 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.
$ 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 : FalseDoes 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.
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 differOn 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.
print(" rates.py body is running")
RATE = 1.08import 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)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 TrueThree 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.
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.2from service import tax_rate # ❌ TRAP: service is still half-loaded when this line runs
RULES = [lambda order: order * (1 + tax_rate())]# 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.
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.
# 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.
- Restructure: move the shared piece (here
tax_rate) into a third module that both import. The dependency now points one way only. - Import the module, not the name:
import rulesand then writerules.RULESinside functions. The lookup ofRULEShappens at call time, after both modules have finished loading. - Import inside the function: a local
from rules import RULESinsideprice()runs only when called. It hides the cycle rather than removing it, so use it for a cycle you cannot restructure yet.
def tax_rate(): # ✅ shared piece moved into a third module
return 0.2from rates import tax_rate
RULES = [lambda order: order * (1 + tax_rate())]import rules # ✅ import the module object; look names up at call time
def price(order):
return sum(rule(order) for rule in rules.RULES)12.0With 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.
- Works: a layered design where low-level modules (money, rates) never import high-level ones (service, API). Type-only imports can use
if TYPE_CHECKING:so they do not run at start-up. - Fails: sprinkling function-level imports everywhere. It hides the design problem, adds a dictionary lookup on every call, and moves import errors from start-up to the middle of a request.
- Interview takeaway: "A circular import fails because a module is registered in
sys.modulesbefore its body has finished. I fix the design by moving the shared piece to a third module; a function-level import is the last resort."
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.
import json, decimal, argparse, sqlite3, http.client
print("loaded")$ 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 differThe 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.
- Declare: write
lazy import xorlazy from x import yat the top of the file, exactly where the normal import would go. - Use as normal: nothing else in the code changes.
- 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.
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__)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: moduleBefore 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.
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)decimal loaded before use: False
0.3
decimal loaded after use : TrueThere 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.
$ 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 blocksThere 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.
$ 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: FalseFinally 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.
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 differThe 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.
| Option | Pick it when | Cost 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 function | You 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 modules | The 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. |
- Works: command-line tools, serverless functions, anything started often; libraries with optional heavy dependencies.
- Fails: modules whose import has a needed side effect, such as registering a handler or a plugin, and code that must fail fast when a dependency is missing.
- Interview takeaway: "I find start-up cost with
-X importtime. In 3.15 I uselazy importat module scope so unused modules never load; before that, a function-level import, knowing it hides dependencies."
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.
import multiprocessing as mp, sys
print(f"Python {sys.version.split()[0]} on Linux: default start method = {mp.get_start_method()}")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 = forkserverOn 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.
- Keep definitions at the top level: functions and classes that workers need must be importable.
- Put the launch under the guard: creating the pool and calling
mapbelong inif __name__ == "__main__":. - No work at import time: do not start threads, processes or servers just by importing.
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))))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.
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))))[0, 2, 4, 6]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))))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.
- Works: every script that uses
multiprocessingorProcessPoolExecutor, and any module that should be importable without side effects. - Fails: expensive top-level work (loading a model, opening a database) still runs in each worker even with the guard, because it is outside it. Put such work inside a function that the worker calls on purpose.
- Interview takeaway: "
spawnandforkserverre-import the main file in each worker, so process creation must sit underif __name__ == '__main__'. The Linux default changed from fork to forkserver in 3.14."
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.
- Find the loop: profile first (section 07); do not guess.
- Keep data in one typed array: a numpy array holds raw numbers side by side, not 5 million separate objects.
- Express the rule on the whole array:
arr * 1.2 + 0.5instead of a loop.
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())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 differRead 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.
| Option | Pick it when | Cost or catch |
|---|---|---|
Built-ins (sum, map, min) or algebra | The rule is simple and no new dependency is acceptable. | Limited to what the built-ins can express. |
| numpy arrays | Many 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. |
- Works: arithmetic over columns of numbers: prices, sensor readings, scores.
- Fails: loops with branching and dictionary lookups per item, small inputs, and code that is slow because of I/O rather than arithmetic.
- Interview takeaway: "I profile first, and if the hot loop is numeric I move it into numpy or another C-level loop. On our test the heavier rule ran about 7.6 times faster, and I measure with real sizes."
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.
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.
# 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| How the call is made | Total for 50 calls | What the p99 customer feels |
|---|---|---|
await asyncio.sleep(0.1) | 0.10 s | All 50 waits overlap, so everyone waits one call's time. |
time.sleep(0.1) inside async def | 5.01 s | The 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 s | Fifty 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.
| Model | What the workers share | Best for | Cost 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. |
| asyncio | Everything, 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.
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.
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())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 tracebackRead 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.
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.
- Pop: take the first task from the ready queue.
- Run until it awaits: the task runs ordinary Python code until it reaches an
awaiton something that is not finished yet. At that point it hands control back. - Register the wait: the thing being awaited (a socket read, a timer) is registered with the selector, which watches it for the operating system.
- 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.
- 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.
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:
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 eachLook 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.
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)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 secondsThe 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.
- 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). - Size the pool: the default pool has
min(32, cpu_count + 4)threads. For heavier use, create your ownThreadPoolExecutorand useloop.run_in_executor(pool, fn, arg). - Prefer a real async library when one exists: a thread costs memory and a context switch, an async client costs neither.
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())price-for-pizza price-for-fries
default executor workers: 16- Works: a handful of blocking calls per request, legacy libraries with no async version, short file or CPU-light work.
- Fails: CPU-heavy pure-Python work. A worker thread still needs the GIL, so it still steals time from the loop thread. Use a process pool for that (later in this section).
- Interview takeaway: "Blocking code in an async handler freezes every task. I move it to a thread with
asyncio.to_thread, and I remember that the default pool is 16 on a 12-core box, not infinity."
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.
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)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 tracebackThe 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.
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.
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.
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.
--- 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 demoWith 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.
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.
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)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.
- Open the group:
async with asyncio.TaskGroup() as tg:and start children withtg.create_task(coro()). - Collect results from the tasks: keep the task objects and read
task.result()after the block, when you know every one is done. - Handle failures with except*: wrap the whole
async withintryand useexcept*for each error type you can handle. Let the rest propagate. - 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 ---
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 demoWith the idiom (the next six lines): the siblings are cancelled and the error arrives as a group, after everything has stopped.
--- 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- Works: fan-out inside one request (three lookups, N pages), any set of tasks whose results you need together, anything that must not leak work after an error.
- Fails: when you really want "run all, give me every result including failures". Then
gather(..., return_exceptions=True)is the right tool, because a group cancels on the first failure. It also does not suit tasks that must outlive the request (background jobs); those need an owner somewhere else (see the idiom after the next one). - Interview takeaway: "
gatherreports the first failure but leaves the others running, so I get orphan tasks.TaskGroupcancels the siblings and raises anExceptionGroupafter all have stopped, so I handle it withexcept*."
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.
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()) 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 itRead the output in four parts.
- Swallowed cancel:
swallow()printed "ignoring it", and afterwardsdone()is stillFalse. The task never stopped. In a real service this is a worker that cannot be shut down, and a deploy that hangs until the platform kills it. - Polite worker:
polite()ran itsfinallyblock, let the error through, anddone()isTrue. - Timeout:
asyncio.timeout(0.2)cancelled the slow call after 0.2 s and turned the cancel into aTimeoutErrorat theasync withline. It replaces the olderasyncio.wait_forin most code (3.11+). - Shield:
asyncio.shield(inner)let the caller stop waiting after 0.1 s without cancelling the inner task. The payment save still finished. Use it for work that must complete even if the caller gives up, and keep the shielded part small.
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.
- Add the task to a set that lives as long as the application:
background.add(task). - Remove it when it ends:
task.add_done_callback(background.discard). The set cannot grow forever. - Better, give the task an owner: start it in a
TaskGroupthat 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.
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())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: 0The 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.
- Works: audit logs, metrics pushes, cache warm-ups, any "do this soon, I do not need the answer" work, with a module-level set or an application-level
TaskGroup. - Fails: a set of tasks whose exceptions nobody reads. The reference keeps the task alive, but an error inside it still goes unseen until the task is garbage collected. Add a done callback that logs
task.exception(). - Interview takeaway: "The loop holds tasks weakly, so a fire-and-forget
create_taskcan be garbage collected mid-flight. I store it in a set and discard it in a done callback, or better, I run it in aTaskGroup."
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.
- Create the semaphore once and share it with every task:
sem = asyncio.Semaphore(10). - Hold it only around the outbound call, not around the whole task:
async with sem: await client.get(url). - 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.
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))# 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=100The 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".
- Works: protecting a partner API, a database pool, or a file-descriptor limit from your own fan-out. One semaphore per resource.
- Fails: as a rate limit. A semaphore limits how many at once, not how many per second. Ten fast calls per 100 ms is still 100 calls per second. For "N per second" you need a token bucket. Also, it is not shared across processes: ten worker processes with a limit of 10 each is 100.
- Interview takeaway: "I bound outbound concurrency with
asyncio.Semaphorearound the call, and I check the maths: 100 calls × 0.1 s ÷ 10 = 1.0 s. A semaphore is not a rate limiter."
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.
- Declare once at module level:
request_id = ContextVar("request_id", default="-"). - 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. - Read anywhere below: logging filters and deep functions call
request_id.get(). - Threads started with
to_threadinherit it:to_threadcopies the current context into the worker thread, which a plainthreading.Threaddoes 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.
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:
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-CLook 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.
- Works: request ids, trace ids, the current tenant, the current user, in async and in threaded code. Web frameworks and logging libraries rely on this.
- Fails: as a hidden global for business data. Anything the function needs to compute its answer should be an argument, because a context variable is invisible in the signature, which makes the function harder to test. Also, a value set inside a task is not visible to the parent after the task finishes.
- Interview takeaway: "asyncio runs many requests on one thread, so
threading.localis one shared slot.contextvarsgives each task its own copy, andto_threadcarries it into worker threads."
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.
| Tool | What it is | Use it when |
|---|---|---|
ThreadPoolExecutor | A fixed set of worker threads that take jobs and return futures. | You have N independent blocking calls. It is the default choice. |
queue.Queue | A 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.Lock | One 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.Event | A flag that one thread sets and others can wait on or poll. | Clean shutdown: "stop working now". |
threading.local | A 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.
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)[(1, 100), (2, 200), (3, 300), (4, 400), (5, 500), (6, 600)]
counter with a lock: 400000Three 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.
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")--- 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 endsWith 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.
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")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 exitBoth 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.
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.
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.
| Start method | How the worker is created | Good | Catch |
|---|---|---|---|
fork | The 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. |
spawn | A 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). |
forkserver | One 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.
import multiprocessing
import sys
print(sys.version.split()[0], "default start method:", multiprocessing.get_start_method())
print("available:", multiprocessing.get_all_start_methods())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.
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")# 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 sRead it line by line.
- Serial, tiny tasks: 0.003 s. The plain loop does all 20,000 prices in three milliseconds.
- Pool, one task each: 2.03 s. That is about 100 microseconds per task, roughly 700 times slower than the loop. Each task is pickled, written to a pipe, read by a worker, run, pickled again and sent back. The work (about 0.15 µs) is lost in the plumbing.
- Pool, chunksize 1,000: 0.025 s. About 80 times better than the line above, because the plumbing is paid 20 times instead of 20,000 times. It is still about eight times slower than the plain loop, because the work itself is so tiny.
- Heavy tasks: 1.05 s serial, 0.28 s in a 4-process pool. Eight tasks of about 130 ms each. Here the work is more than a thousand times bigger than the plumbing, and 4 processes give a 3.8 times speed-up, close to the ideal 4.
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.
- Measure the unit first: time one task in the plain loop. If it is under about a millisecond, batch many items into one task.
- Batch with
chunksizeor explicit chunks:pool.map(fn, items, chunksize=1000), or send a list of 1,000 items as one argument and return one list. - 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.
- Create the pool once and reuse it (
with ProcessPoolExecutor(n) as pool:at start-up). Starting workers costs tens of milliseconds each. - 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):
pool, 20,000 tasks, chunk=1 3.111 sWith the idiom (batched, then genuinely heavy tasks):
pool, chunksize=1,000 0.020 s
serial, 8 heavy tasks 1.008 s
pool(4), 8 heavy tasks 0.282 s- Works: image resizing, parsing big files, price rules that cost milliseconds per order, anything CPU-bound with small inputs and outputs.
- Fails: sub-millisecond tasks, tasks that need a shared live object (a connection, a big dictionary you update), and anything that must keep global state in sync across workers.
- Interview takeaway: "A process pool pays for pickling on every task, so I batch the work into units of milliseconds or more and send ids and paths, not big objects. On 3.14 the default start method is
forkserver, so I guard the main module."
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.
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())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: 1Four things to read off the output.
- Code runs inside it:
interp.exec(source)ran a string of code in the second interpreter and printed from it. - Isolation is real: the main program has
counter = 5, yet the subinterpreter raisedNameErroroncounter. Nothing is shared by default. - Calling functions works, with copying:
interp.call(square, 12)sent the function and the argument over and got144back. Arguments and results must be of simple, shareable kinds. - A pool exists:
InterpreterPoolExecutorhas the same shape asThreadPoolExecutorandProcessPoolExecutor, 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.
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)# 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# same script, same machine
serial 1.137 s
ThreadPoolExecutor(4) 0.295 s
InterpreterPool(4) 0.375 s
ProcessPool(4) 0.318 s| Model | Python 3.14 (GIL) | Python 3.14t (no GIL) | Reading |
|---|---|---|---|
| Serial loop | 1.025 | 1.137 | The baseline. |
| 4 threads | 2.532 | 0.295 | With the GIL, slower than serial. Without it, 3.9 times faster than serial on this run. |
| 4 subinterpreters | 0.317 | 0.375 | About 3.2 times faster than serial on the standard build, with no process start-up. |
| 4 processes | 0.307 | 0.318 | About 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.
| Option | Pick it when | Cost 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. |
ProcessPoolExecutor | Pure-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.14t | Many 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 machines | One 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.
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__)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.
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.
# 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'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.
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)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>.
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.
Runtime type is 'int'
Runtime type is 'str'
Runtime type is 'tuple'
1 pizza (2, 1) tuple[T, T]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.
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 literalsliteral_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").
- Declare the shape:
class PriceRule(Protocol):with the method signatures and...bodies. - Use it in signatures:
def run(rule: PriceRule, ...). Callers pass anything that fits. - 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.
- Add
@runtime_checkableonly if you needisinstanceagainst the Protocol. It checks that the names exist, not the signatures.
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 laterWhat you see: Python runs the first call, fails on the second only when it is reached, and the checker rejects it before.
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'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.
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.
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.
- Works: plug-in points, test fakes, any place where "anything with an
applymethod" is the real requirement. Pair it with generics, as theRuleBook[R: PriceRule]class in the ladder below does. - Fails: when you need shared code or
isinstancechecks at run time. An abstract base class (abc.ABC) gives you both: a place to put shared methods and a check at instantiation that abstract methods are filled in. Also, a Protocol checks nothing at run time by itself. - Interview takeaway: "A Protocol is structural typing: the checker compares shapes, not names, so I can type a plug-in point without forcing inheritance. I still use an ABC when I want shared implementation or run-time enforcement."
| Option | Pick it when | Cost or catch |
|---|---|---|
TypedDict | You 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). |
@dataclass | Internal values with behaviour: methods, defaults, frozen=True. | No validation at all. The annotations are still only notes. |
Pydantic BaseModel | Data 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. |
attrs | Like 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.
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"))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=125The 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.
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.
| Option | Pick it when | Cost or catch |
|---|---|---|
| mypy | The 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). |
| pyright | You 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.
- Declare the type parameters:
def logged[**P, R](fn: Callable[P, R]) -> Callable[P, R]:. - Type the wrapper with the same names:
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:. - Keep
functools.wraps(fn)so the name and docstring survive at run time (Part B's idiom). - Add or remove a first argument with
Concatenatewhen the decorator injects a parameter (below).
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 itMake the invisible visible: what mypy thinks each decorated function is.
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.
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))concat_decorator.py:20: note: Revealed type is "def (cents: int) -> str"
Success: no issues found in 1 source fileRuntime type is 'function'
r-1: 250The 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.
- Works: logging, timing, retry, caching and auth decorators in any codebase that runs a type checker.
- Fails: decorators that change the return type by wrapping it (a decorator that turns
intintoResult[int]needsCallable[P, Result[R]]), and class-based decorators, which need__call__typed by hand. If the typing gets harder than the code, a plain function without the decorator is fine. - Interview takeaway: "An untyped decorator erases the wrapped function's signature, so the checker accepts any call.
ParamSpeckeeps it, andConcatenatehandles decorators that add or remove an argument."
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.
Traceback (most recent call last):
File "<string>", line 2, in <module>
File "<string>", line 3, in Order
NameError: name 'Customer' is not definedThe 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.
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))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.
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}")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.
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.
home = /usr/bin
implementation = CPython
uv = 0.12.5
version_info = 3.12.3
include-system-site-packages = truehome = /usr/bin
implementation = CPython
uv = 0.12.5
version_info = 3.12.3
include-system-site-packages = false
prompt = quickbite-pricerLook 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.
[project](PEP 621): the name, version, minimum Python (requires-python), the dependencies, and optional groups of them such asdev.[build-system]: which tool turns your source folder into an installable package. This tool is the build backend (hatchling, setuptools, uv_build, flit). Installers read this table, download the backend, and call it. You never call it by hand.[tool.*]: settings for pytest, mypy, Ruff and others, so one file configures everything.
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.
- Declare ranges in
pyproject.toml: what you need and the oldest version you support.uv add httpxwrites the line for you. - Resolve once into
uv.lock:uv lock(run byuv addtoo) picks exact versions for the whole tree and writes hashes. Commit this file. - Install from the lock everywhere else:
uv sync --frozenin CI and in the Docker build.--frozenmeans "use the lock as it is, do not re-resolve".--lockedis similar but fails if the lock is out of date withpyproject.toml. - Upgrade on purpose:
uv lock --upgrade-package httpxin 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 --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[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.
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...
]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.20The 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.
- Works: applications and services, where you want the same bytes in development, CI and production, and can see every library change in a diff.
- Fails: libraries that other people install. A library should publish loose ranges (
httpx>=0.28) so users can combine it with other libraries. Lock your library's development environment, not what you ask users to install. A lock also does not remove the need to upgrade: a locked vulnerable version stays vulnerable until you bump it. - Interview takeaway: "A range in
pyproject.tomlis a wish. The lockfile pins the whole tree with hashes. CI and Docker runuv sync --frozen, and upgrades happen in their own reviewed change."
| Option | Pick it when | Cost or catch |
|---|---|---|
| uv | New 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-tools | You 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. |
| Poetry | You 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). |
| PDM | You want a standards-first manager with a lockfile and PEP 621 metadata. | A smaller community than Poetry or uv. |
| conda | Native 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).
import os, sys
from decimal import Decimal
def total( items ):
t=0
for i in items :
t = t+ i
unused = Decimal("1")
return truff_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`).--- 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 reformattedThe 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.
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
[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.11sThe 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.
- Write the fixture once in
conftest.py, returning a fresh object each time (a new list, a newRuleBook). - Request it by parameter name:
def test_x(basket, book):. No imports, no setup lines. - Use
yieldfor cleanup: close connections or delete files after theyield, so cleanup runs even when the test fails. For files, prefer the built-intmp_pathfixture, which pytest creates and removes for you. - 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.
- Works: readable tests (the test body shows only what is special), independent tests that can run in any order or in parallel, one cleanup path.
- Fails: when fixtures chain five levels deep and nobody can tell what a test uses. Keep them shallow, name them for what they are, and let a plain helper function do the rest. Also avoid a widely-scoped fixture that tests mutate: that is a shared global in disguise.
- Interview takeaway: "A fixture builds the test's data and cleans it up after
yield. I default to function scope so tests cannot leak state, and widen to session only for expensive read-only resources."
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.
- Find the line in the code under test that uses the thing:
fetch_tax_rate(region)inservice.py. - Check how it got there:
from x import ymeans patch"module_under_test.y".import xthenx.y()means patch"x.y". - Prefer
monkeypatch.setattr(undone automatically) or pass the dependency in as a parameter, so the test needs no patching at all.
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.
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.16sThe 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.)
- Works: faking network calls, clocks and randomness at the edge of the module under test.
- Fails: as a habit. A test with four patches knows too much about the code's insides and breaks on every refactor. Where you can, pass the dependency as an argument, or use a small fake object (the Protocol idiom helps here), and keep
patchfor the last resort. - Interview takeaway: "Patch where the name is looked up, not where it is defined. After
from a import b, the code under test usesits_module.b, so that is the name I replace."
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.
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) == expectedF [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.32sHypothesis 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.
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)# 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 sStep 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.
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.
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")# 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,119xWith 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.
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")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.
- Time a small piece:
timeitfor a statement, ortime.perf_counter()around a call. Always repeat; the first run is often different. - Profile the whole run:
cProfile+pstats(built in, deterministic, adds overhead) tells you which functions to look at. - 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 theprofiling.samplingpackage. - 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.
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")# 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 nameIt 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.
- Works: finding the one hot function out of hundreds, comparing a fix with the original, and settling an argument with a number.
- Fails: on tiny benchmarks that do not look like production (data size, concurrency), and on code that spends its time waiting. A CPU profile shows nothing for a function that sleeps on the network. For that, use a wall-clock mode, or tracing, or look at the loop with debug mode (earlier in this section).
- Interview takeaway: "I measure before I change anything:
timeitfor a statement,cProfilefor functions, a sampling profiler for a live process. I change one thing and measure again, and I keep the before and after numbers."
| Option | Pick it when | Cost or catch |
|---|---|---|
| A better algorithm or data structure | Always first. The set in the demo gave about 110 times with no new tools. | Needs a profile to find, and some thought. |
| numpy | The 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. |
| numba | A 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. |
| Cython | You 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 maturin | A 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/.
-
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
[build-system]says hatchling builds the package.[project]gives the name, version andrequires-python = ">=3.12". There are no runtime dependencies.[project.optional-dependencies] devlists pytest, hypothesis and mypy.[tool.pytest.ini_options]addssrcto the import path, so tests find the package without installing it.[tool.mypy] strict = trueturns 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);srclayout.from the
pricerfolder, read the file withtomllib. It prints the name, the minimum Python and the dev tools.output · Python 3.12.3runs offlinepricer >=3.12 ['pytest>=9', 'hypothesis', 'mypy'] -
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
@dataclass(frozen=True, slots=True)makes an immutable, hashable, small-memory class.amountis aDecimal, never a float, so 0.10 + 0.20 is exactly 0.30.Money.of("9.50")builds one from text and rounds to cents with half-even rounding.__add__refuses to mix currencies;timesmultiplies and rounds.
src/pricer/money.py — chunk 2runs offlinefrom 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=Truefrom Section 02, andDecimal.quantizewithROUND_HALF_EVEN.from the
pricerfolder run Python withPYTHONPATH=srcand add two Money values. You should see exact cents, aFrozenInstanceErroron assignment, and a Money used as a dict key.output · Python 3.12.3runs offline0.30 EUR FrozenInstanceError usable as a dict key -
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
findreturnsNonewhen a code is unknown.Step-by-step: what this chunk does, in plain English
PriceRule(Protocol)listsnameandapply.PercentOffandFlatOffare frozen dataclasses. Neither mentionsPriceRule.RuleBook[R: PriceRule]is a generic class (3.12 syntax), bounded by the Protocol.findis typedR | None, so the checker makes every caller deal with a missing code.
src/pricer/rules.py — chunk 3runs offlinefrom 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)Protocoland 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 offline10.75 EUR 16.50 EUR None 1 -
Chunk 4 — the service, with the None case handled
Tuesday's incident lives here.
price_ordercallsfind, and theif rule is not Nonebranch is what the checker demands. The tax rate comes fromrates.py, which stands in for an HTTP call.Step-by-step: what this chunk does, in plain English
LineItemis another frozen dataclass: sku, unit price, quantity.subtotaladds up the lines with exact money arithmetic.price_orderapplies the code only if it is given and known, then adds tax.fetch_tax_rateis imported by name withfrom ... import, which matters for the patch test in chunk 6.
src/pricer/rates.py — chunk 4runs offlinefrom 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 offlinefrom 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 Nonethe checker knowsruleis 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 offline25.58 EUR 12.79 EUR 25.58 EUR -
Chunk 5 — fixtures and unit tests
The package works, so now we make that permanent.
conftest.pybuilds a fresh rule book and basket for every test, and the tests for money and rules useparametrizeand a Hypothesis property.Step-by-step: what this chunk does, in plain English
@pytest.fixturefunctions return new objects each time.test_rulesruns four input rows through one function withparametrize.test_money_is_immutable_and_hashablechecks the frozen behaviour from chunk 2.test_addition_commutesis a Hypothesis test: it generates the numbers.
tests/conftest.py — chunk 5runs offlinefrom 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 offlinefrom 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 + xtests/test_rules.py — chunk 5runs offlinefrom 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.pyfixtures,@pytest.mark.parametrize,@given.run
pytest -qon 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 -
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
- Hand-computed numbers in comments: 21.50 + 19 percent = 25.585, half-even gives 25.58.
patch("pricer.service.fetch_tax_rate")replaces the name where the service looks it up.patch("pricer.rates.fetch_tax_rate")changes nothing, so the test asserts the price is still taxed.monkeypatch.setattrdoes the first job with automatic undo.
tests/test_service.py — chunk 6runs offlinefrom 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.patchandmonkeypatchwith 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 -
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
pytest -qruns all 15 tests. I added-p no:deepevalonly because the course venv has an unrelated plugin that prints an extra line.mypyreadspyproject.tomland checkssrcandtestsin strict mode.ruff checkandruff format --checklint 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 formattedStrict mypy: every function in
srcandtestshas full annotations, and the genericRuleBook[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 Noneline inservice.pyand 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.
# ── 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.
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.
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))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: 2What 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."
- "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[:]andb = 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 onlyb, 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
99added througha, and the deep copy does not.q01_copy.py (output)runs offlinea [[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.
- What it is: In CPython,
id(x)returns the memory address of the objectxpoints at, as a plain integer. Two names with the sameidare labels on one object, which is exactly whatistests. - 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
idvalues taken at different times can match. - 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
idfor debugging and for demos like Q1, andisfor real identity checks. I never store anidas 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. - What it is: In CPython,
- "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. Thent += "c"builds a new string"abc"and moves the labeltonto it. The namesstill 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, sob += [4]changes whatasees 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 listOne 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, sob.add(3)shows througha. 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 changingycan never touchx. Python has no primitives. A Pythonintis a full object with a reference count and a type pointer, about 28 bytes for a small one, andy = xjust 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 toarrayor 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.
# 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}")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 -> FalseWhat 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.
- "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 seesx is 257orx is "abc". It appears at compile time, before the program runs.The reason is that this bug hides well.
x is 5works 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::SyntaxWarningin 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 deserveisareNone,TrueandFalse. - "Why is
x is Noneright whenx == Nonealso works?" -
Two reasons, one about correctness and one about speed.
- Nobody can fool it: A class may define
__eq__so that it claims to equalNone. Some array libraries return a whole array of True/False fromarr == None, which then breaks anif.x is Nonecompares addresses, and there is exactly oneNoneobject in the process, so no class can change the answer. - It is cheaper:
iscompares 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. - It is the style rule: PEP 8 says comparisons to singletons such as
Noneshould useisoris not, and linters flag== None.
So
x == Noneusually 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. - Nobody can fool it: A class may define
- "When do two equal objects not have the same identity?"
-
Almost always, for anything that is not cached.
[1] == [1]isTruebecause the contents match, and[1] is [1]isFalsebecause 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 offlineTrue 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 whyx == xis not a safe test for "x is a normal value", and why float keys in dicts deserve suspicion. - "Can I make
isreturn 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 andissaysTrue. 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.internThe first list is a check of each string against the first, so the leading
Trueis 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 onisis 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.
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__)['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.
def add(item, bucket=[]):
bucket.append(item)
return bucketPython idiom
None means "make a new one".
def add(item, bucket=None):
if bucket is None:
bucket = []
bucket.append(item)
return bucketThe 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.
- "Is a mutable default ever useful on purpose?"
-
Yes, as a deliberate cache.
def fib(n, memo={})stores results in the dict that lives infib.__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
Noneis a legal value for the argument?" -
Then
Nonecannot also mean "the caller gave me nothing", so you need a marker nobody else can produce.- Create the marker once: At module level write
_MISSING = object(). A bareobject()is a new, featureless object that equals nothing but itself. - Default to it:
def add(item, bucket=_MISSING):. The default is evaluated once, which is fine here, because the marker is never mutated. - Test with is: Inside, write
if bucket is _MISSING: bucket = []. A caller who passesNonenow getsNonethrough, 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 theobject()idiom for code that must run on 3.12 and 3.14. - Create the marker once: At module level write
- "Do linters catch this?"
-
Yes. Ruff has rule B006 (mutable argument default) and pylint has W0102 (dangerous-default-value). Both flag
[],{}andset()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
defruns.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
Noneplus 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
bucketappends 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.
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)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.
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.
def mutate(xs):
xs.append(1) # caller sees it
def rebind(xs):
xs = [] # caller does notThe 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.
- "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, orsorted(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.deepcopyis the safer choice (Q7).A naming convention helps readers. Methods such as
sort,appendandextendmutate and returnNone. Functions such assortedreturn 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.
- The rule: A method that changes the object in place returns
None. That way you cannot writey = xs.sort()and believe thatyis a new sorted list whilexschanged under you. - The classic mistake:
xs = xs.sort()sorts the list and then rebindsxsto the return value, which isNone. The next line fails with'NoneType' object is not iterable. - The fix: Use
xs.sort()on its own line when you want in-place, orxs = 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.updateandset.add. Python borrowed it from the idea of command-query separation: a call either changes something or answers a question, not both. - The rule: A method that changes the object in place returns
- "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 names. 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 aswap(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 nameitemsfroma1to the class, finds the one list, and changes it. Nowa2.itemsshows[1]. Comparea1.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 usefield(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.
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)))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: TrueWhat 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.
- "Why is
hash(1) == hash(1.0)and does it matter?" -
It follows from one rule: if
a == b, thenhash(a)must equalhash(b). Since1 == 1.0isTrue, 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 offline1 1 1 {1: 'b'} 1The first line includes
hash(True), becauseTrue == 1too. Settingd[1.0] = "b"did not add a second key. It overwrote the value under the key1.It matters for data from JSON or CSV, where the same id may arrive as
1in one record and1.0in 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__toNonefor 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
frozensetthe same as a set that never changes?" -
Yes in behaviour, with one extra ability, and one cost to know about.
- The ability: A
frozensetis 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 fromfrozenset({"A", "B"})to a route, where order must not matter. - 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.
- 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
frozensetwhen the set is a value (a key, a constant, a field of a frozen dataclass), and a plainsetwhen I am building or updating it. In short, it is a set that promised not to move. - The ability: A
- "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 linet[0].append(9)works, because it never assigns into the tuple; it follows the reference and mutates the list. The linet[0] = [9]raisesTypeError, 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 withunhashable 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.
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"))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_VALUEWhat 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.
- "How do I extend that inner list without the error?"
-
Skip the store.
t[0].extend([3])andt[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 noTypeErrorcan happen.The reason this works where
+=fails is the number of steps.t[0] += [3]is fetch, in-place add, then store intot[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 statementa += bmeans: iftype(a)has__iadd__, seta = a.__iadd__(b); otherwise seta = a + b.A list defines
__iadd__. It extends itself and returnsself, so the "rebinding" lands on the same object. A string has no__iadd__, sos += "x"becomess = s + "x", which builds a new string and moves the label.This is why
a += banda = a + bare not the same for lists. The first changes the one list every name sees. The second builds a new list and moves only the namea. Two names for one list,x = y = [], make the difference visible:x += [1]changesy, andx = 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.
- 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. - 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.
- 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.
- Each step is atomic by itself: Fetching an item, calling
- "Does the same thing happen with dictionaries?"
-
Yes, the same three steps appear. With
d = {"k": [1]}, the lined["k"] += [2]is: fetchd["k"], call__iadd__on the list, then calld.__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
MappingProxyTyperefuses__setitem__, yet the list inside was already extended. The run shows it.q06_dict_proxy.py (output)runs offlineTypeError: '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 calld["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.
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"])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.
b = base.copy()
a = base.copy()
a["fees"].append("x")
# base, a, b all changedDeep or frozen
New contents, or no edits.
a = copy.deepcopy(base)
b = copy.deepcopy(base)
a["fees"].append("x")
# only a changedThe 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.
- "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)andcopy.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.deepcopyis 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
deepcopyas 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 offlineTrue False TrueThe three values mean:
c["a"] is c["b"](sharing kept),c["a"] is shared(the copy is new, not the original), andc["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.
- Freeze the shape: A frozen dataclass whose fields are tuples, or
MappingProxyTypeover the top-level dict with tuples below. Any attempt to edit raises an error at the line that tried. - 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.
- 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') - Freeze the shape: A frozen dataclass whose fields are tuples, or
- "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
aandbfrombase; call each mutating method ona(add a fee, change a tax rate); then assert thatbequalsfresh_from_base(). A second line assertsaequals 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 nestedlist,dictorsetfield, 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.
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))identifier-like literal, two units : True
literal with space and '!' : False
built at runtime, equal : True identical: False
after sys.intern : TrueWhat 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.
- "How much memory can interning save?"
-
Take a worked example, and measure the one number it hangs on.
- 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. - Without interning: 5 million rows, each with its own
statusstring 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. - 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.Categoricalis usually cleaner, because it also stores each row as a small integer code. - Size of one string: On my 3.12 build,
- "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.internlive 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 thesys.interndocumentation 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 tos, 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
tracemallocbefore 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, andnew 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 printsTruein a file. A string built at runtime, such as"".join(["a", "bc"]), is a new object andissaysFalse.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,FalseandEllipsis, 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
isfor 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 useisonly forNoneand 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.
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))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? FalseWhat 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.
- "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.
- 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. - A hashable key: A proxy is not hashable. Use
tuple(sorted(d.items()))orfrozenset(d.items()), which works when the values are hashable, and rebuild a dict when you need lookups. - A drop-in type: A third-party package called
frozendicthas 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. - Read-only view of data you own:
- "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 offlineTypeError: 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
TypeErrorin 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
finalin 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)isFalse, whileisinstance(fd, collections.abc.Mapping)isTrue. The run printed those two values on one line:q09_frozen.py (3.15.0rc1 output, first line)runs offlineFalse TrueThe consequence is that code which checks
isinstance(x, dict)will reject a frozendict. This catches people who write JSON encoders and validators that special-casedict.The habit that avoids it is to accept
collections.abc.Mappingin function signatures and checks. Then callers can pass a dict, aMappingProxyType, afrozendictor 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.
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)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 EURWhat 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.
public record Money(
BigDecimal amount,
String currency) {
public Money {
amount = amount.setScale(2,
RoundingMode.HALF_EVEN);
}
}Python
Frozen dataclass with Decimal.
@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.
- "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.
- 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
BIGINTcents is simple and has no rounding surprises. - 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.
- Where Decimal helps:
Decimalkeeps 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,
Decimalwhen percentages and several currencies are everywhere. Here is the arithmetic for 8.25 % tax on 19.99:worked exampleruns offline19.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) - 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
- "Why does
Decimal(0.1)print a long number?" -
Because
0.1as 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 offline0.1000000000000000055511151231257827021181583404541015625Decimal("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
floatin__post_init__with a clear message and acceptDecimal,intorstr. At system edges, such as JSON parsing, I read numbers as strings, or use a parser option that yieldsDecimal. - "What is banker's rounding and why choose it?"
-
ROUND_HALF_EVENrounds 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 offlinevalue half_even half_up 2.665 2.66 2.67 2.675 2.68 2.68 2.685 2.68 2.69In 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=Trueworth 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 = 3raisesAttributeErrorinstead 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.
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.
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())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.
x = Noisy("A")
x = None
# __del__ runs on this lineCycle collector
Freed later, in batches.
a.other, b.other = b, a
a = b = None
# nothing yet; gc.collect()
# or the next gen-0 runThe 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.
- "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
xto the function creates a temporary extra reference for as long as the call runs.q11_refcount.py (output)runs offline2 only the name a, plus the call's own argument 3 after b = a: two names, plus the argument 2 after del bThe first line makes the +1 visible: a list with a single name reports 2. After
b = athe count is 3, anddel bbrings it back to 2. In Q1 the list had the labelsaandb, so the call printed 3.I use
getrefcountfor 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.
- 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). - 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.
- 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.
- It dirties memory pages: Every time code passes an object around, the count in its header is written. After
- "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.callbackshook (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.
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")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 MBWhat 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.
- "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 withcollections.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 millionSessionobjects.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
tracemallocwill not see it, so I switch tools in three steps.- Confirm: RSS grows while the
tracemalloctotal stays flat. That says Python's own allocator is not where the memory goes. - Use a native profiler:
memraycan trace native allocations too, andvalgrindorheaptrackwork at the C level. They are slower, so I run them on a copy of the service with a small, repeatable load. - 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.
- Confirm: RSS grows while the
- "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
weakreffor 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 thetracemallocsnapshot 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).
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")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 differWhat 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.
- "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.
- 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.
- 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. - Recycle workers: Let a worker exit after N jobs and the operating system takes back everything. Gunicorn's
max_requestsand Celery'smax_tasks_per_childdo exactly this.
I would add jitter, for example
max_requests_jitterin 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_trimand 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 withctypes:ctypes.CDLL("libc.so.6").malloc_trim(0). It is not Python-specific.It helps for memory that came from
mallocdirectly: 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
tracemallocis 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
forkand 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 withsmemor/proc/<pid>/smapsbefore 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.
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")getsizeof(list) : 8856 bytes
list + each string (deep) : 148856 bytes
tracemalloc, what was held : 149264 bytes
one string : 140 bytes for 100 charactersWhat 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.
sys.getsizeof(items)
# 8856 bytes for 1,000 itemstracemalloc
Everything allocated.
tracemalloc.start()
items = build()
tracemalloc.get_traced_memory()
# about 150 KBThe 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.
- "How do I write a deep size function?"
-
Write a small recursive walk, and keep a record of what you have counted.
- Keep a seen set: Start with
seen = set()ofid(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. - Add the shallow size: For each new object add
sys.getsizeof(obj). - 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.asizeofalready do it, including the awkward cases, so I use one for anything beyond a quick check. I still confirm withtracemalloc, because a walk can miss memory held by C extensions that do not expose their contents. - Keep a seen set: Start with
- "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 offline0 56 1 88 5 120 9 184 17 248 25 312 33 376The 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
appendstays cheap on average.getsizeofshows capacity, not length, so8 * len + 56is only a lower bound. - "Why does a
dictlook 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, andgetsizeofdoes 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
tracemallocfigure 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
getsizeofalone gets one comment from me: please re-measure withtracemalloc.
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.
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))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.
cache = {}
cache[obj.id] = obj
del obj
# still alive in cacheWeakValueDictionary
The cache only watches.
cache = WeakValueDictionary()
cache[obj.id] = obj
del obj
# entry removed automaticallyThe 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.
- "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
Customerobject 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
intor alist?" -
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 offlineTypeError: 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 okA subclass of
listworks (theTrueline), because a class defined in Python gets the slot automatically. A class with__slots__loses it unless"__weakref__"is listed, shown bySandSW.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.- The call:
weakref.finalize(obj, callback, *args)registerscallback(*args)to run whenobjis freed. It lives outside the object, so it works for classes you do not own. - The one rule: The callback must not hold a strong reference to
obj, directly or through a bound method. If it did,objcould never die. Pass what it needs, such as a file descriptor or a path, as arguments. - The extras: It runs at most once. You can call it yourself (
f()), detach it withf.detach(), and it is run at interpreter exit by default, which you can switch off withf.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. - The call:
- "How does Java compare?"
-
Java has
WeakReference,WeakHashMapandSoftReference, 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 offline1 0The first line is the dictionary length while
ostill exists, and the second is right afterdel 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.
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")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 exceptionWhat 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__.
class Conn:
def __del__(self):
self.sock.close()
# when? maybe neverExplicit
Cleanup you control.
with Conn() as conn:
conn.query()
# __exit__ closes it here,
# even if query() raisesThe 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.
- "Why does it sometimes not run at interpreter exit?"
-
At shutdown, CPython tears the program down in a fixed order: it runs
atexitcallbacks, 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 asosor your own logger can beNone, and you getAttributeError: '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" isatexit.register(func), which runs while everything is still intact. The reliable tool for "release when this block ends" iswith. - "What is
weakref.finalizedoing better?" -
weakref.finalizeregisters 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 offlineimport 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, notself. If the callback referred toself, the object could never be freed. The finalizer runs at most once, can be run early withself._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
withfor resources a function owns. I usefinalizeas 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.
- 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 ingc.garbageand left them there. Such cycles were a leak. - PEP 442 (3.4): Finalisers now run safely for objects in cycles, and the cycle is collected.
gc.garbageis rare today. - 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
selfsomewhere.
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. - Before 3.4: An object in a reference cycle that had a
- "What does a good test for this look like?"
-
I assert that a resource is released after the
withblock exits, not afterdelor garbage collection. For a file-like helper, the test opens it in awith, leaves the block, and checks thatclosedis 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 aclose()method and a__enter__and__exit__pair. If a finaliser is genuinely needed as a safety net, I ask forweakref.finalizeplus 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.
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()")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.7What 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.
- "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, callgc.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.
- 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.
- 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(). - Safer variants: Raise the threshold, for example
gc.set_threshold(100_000, 20, 20), so collections happen rarely. Or keep it disabled and callgc.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 offlinestart 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().
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")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 differWhat 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.
roots -> mark reachable
sweep / compact
new object = bump pointer
free = "someday, by GC"CPython
Count references, scan cycles.
every assignment: count +1/-1
count == 0 -> free now
cycles -> separate scanner
no compactionThe 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.
- "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.
- CPython: A weak reference dies at the instant the strong count reaches zero.
del objand the entry in aWeakValueDictionarydisappears on the next line, unless the object is in a cycle. - 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.
- Test impact: In Python,
del x; assert key not in cacheusually works. In Java you cannot assert at a given moment, because evenSystem.gc()is only a hint.
That makes a
WeakValueDictionarysimple to test in Python, and aWeakHashMapharder in Java. - CPython: A weak reference dies at the instant the strong count reaches zero.
- "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
withfor files, locks and connections, so cleanup does not depend on who is running your code. I would also avoidsys.getrefcountand__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.
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")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 MBWhat 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.
rows = [Row(i) for i in range(N)]
# N x (object + __dict__)Compact or streamed
No per-record objects.
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.
- "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.
- Aggregations need only running state: Sum, count, max, min and group counts keep one small value per group. A
collections.Counteror a dict of totals can read a stream of 50 million records and stay small. - 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. - 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 offlinefrom 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 - Aggregations need only running state: Sum, count, max, min and group counts keep one small value per group. A
- "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
float64values 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 offlinelist 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 MBThe operations run in C, which is usually much faster than a Python loop. I pick
array.arraywhen 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.freezeand 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.
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 datalist 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 differWhat 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.
- "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.arrayor 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 offlinefrom 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.
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.
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) 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.
int n = basket.size();
Basket c = a.plus(b);
// operators are for primitives
// and String onlyPython
Syntax calls dunder methods.
n = len(basket) # __len__
c = a + b # __add__
# any class can opt inThe 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.
- "Why return NotImplemented instead of raising TypeError?"
-
Because returning
NotImplementedtells Python "I do not know how to handle this partner, ask the other operand". If you raisedTypeErroryourself, 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 offline4.048 TypeError: unsupported operand type(s) for +: 'Meters' and 'str'Meters(1) + Feet(10):Meters.__add__sees a partner it does not understand and returnsNotImplemented. Python then callsFeet.__radd__, which converts and returns4.048meters. With"x"both sides decline, and Python raises theTypeErroritself, with a message naming both types.NotImplementedis 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?" -
leninsists on a non-negative integer from__len__. Anything else is an error, and the run shows the exact messages.q21_len.py (output)runs offline3 ValueError: __len__() should return >= 0 TypeError: 'float' object cannot be interpreted as an integerThe first call is fine, the second returns -1 and raises
ValueError, and the third returns 2.5 and raisesTypeError. For built-in types the call is a fast path in C, solen([...])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 whyif 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.
- The order:
x += ytriestype(x).__iadd__(x, y)first. If the class does not define it, or it returnsNotImplemented, Python falls back tox = x + y, which uses__add__and then__radd__. - 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. - The contract:
__iadd__must return the object that the name should be bound to, almost alwaysself. If you forget the return, the name becomesNone.
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. - The order:
- "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
forloop, I answer__iter__; inwith, 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_orderingbuilds the other comparisons from__eq__and one ordering method, and thecollections.abcmixins give a fullMappingorSequencefrom a few methods. Knowing the list is less valuable than knowing whylen(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.
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")__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 elementWhat 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.
@Override
public boolean equals(Object o) { ... }
// no hashCode() override:
// HashSet misbehaves quietlyPython
Python makes the mistake loud.
def __eq__(self, other): ...
# __hash__ is now None:
# set([...]) -> TypeErrorThe 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.
- "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 rulescould sayFalsefor 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 offlineclass 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 ruleslooks in the old bucket and saysFalse. 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 nofrozen, the dataclass sets__hash__toNone, the same behaviour as in the question. Withfrozen=True, eq=Trueit generates a__hash__from the fields.unsafe_hash=Trueforces one for a mutable class, and the name is a warning. The run shows it.q22_hash.py (output)runs offlineNone True 1 NoneThe 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=Trueis the answer whenever instances are values. I useunsafe_hashnever, 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 returnNotImplementedfor 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.
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)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 2What 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.
rows = [1, 2, 3]
sum(rows) # 6
sum(rows) # 6One-shot
Iterator: one walk only.
rows = (x for x in [1, 2, 3])
sum(rows) # 6
sum(rows) # 0 <- silentThe 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.
- "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 withyield. The older way is to define__getitem__for integer indexes starting at 0, and Python falls back to calling it untilIndexError.iterable class (snippet)runs offlineclass Basket: def __init__(self, items): self._items = list(items) def __iter__(self): yield from self._itemsEach 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
selffrom__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 offlineFalse True 3 0The first line says the list is not its own iterator and the generator is. The second shows
sumrun twice on the same generator: 3 the first time, 0 the second.A defensive function that needs two passes can check
iter(x) is xand calllist(x)first, or its signature can say what it needs. In type hints,Iterable[T]promises one pass;Sequence[T]orCollection[T]promises repeatable iteration and a length. Choosing the right hint documents the contract. - "Why does
fornot 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.
- How it ends:
StopIterationis how an iterator says "I am finished". Theforloop catches it and exits normally, so there is nothing to report. - What an exhausted generator is: It is an iterator whose next call raises
StopIterationat once. To the loop, that is the same as an empty sequence. - 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 asrows_iter, so a second use reads as suspicious. - How it ends:
- "What happens inside
list(gen)andsum(gen)?" -
Each calls
iter()on its argument, then callsnext()repeatedly untilStopIteration, 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,enumerateand theinoperator 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, whilesum([x * x for x in range(10_000_000)])builds the whole list first. Note also thatsortedandlistmust consume everything before returning, so on an endless generator they never finish, whilezipandenumeratestay 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.
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")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
doneWhat 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.
try (var conn = open()) {
conn.query();
} // close() always runs
// suppression: addSuppressedPython
with and __exit__.
with open_conn() as conn:
conn.query()
# __exit__ always runs;
# returning True hides errorsThe 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.
- "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 offlineenter a enter b exit a raised bawas entered, so its__exit__runs.bfailed in__enter__, so it does not exit.cwas never entered, and the body never ran. Python handles this nesting for you, which is one reasonwith a, b:is safer than hand-written nestedtryblocks. - "Does
withgive the block a new scope?" -
No. Names bound inside the block, including the
asname, stay visible after it. Python scopes are for functions, classes and modules, not for blocks, sowith,for,ifandwhileall 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 bothfanddatausable below.fis 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, raisesUnboundLocalErrororNameErrorwhen used later. And a loop variable leaks: afterfor i in range(3),iis 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.
- The methods:
async withcalls__aenter__and__aexit__, which areasync defmethods and are awaited. A synchronouswithon an async manager is an error. - 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. - 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 withasyncio.to_thread. For simple cases@contextlib.asynccontextmanagergives the same short form as the sync version. - The methods:
- "Which standard-library context managers are worth knowing?"
-
The ones I reach for:
openfor files,threading.Lockfor locking,tempfile.TemporaryDirectoryfor scratch space,decimal.localcontextfor scoped precision, andcontextlib.suppressfor one named exception. Alsocontextlib.redirect_stdoutfor capturing output,contextlib.ExitStackfor a variable number of resources, andunittest.mock.patchin tests. Most database drivers make connections and transactions context managers too.In tests,
pytest.raisesis a context manager that swallows exactly the expected exception, and fails the test if none arrives. That is the same idea assuppress, 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.
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)class : 50 ms
generator : 50 ms
open db
open cache
open queue
working with queue
close queue
close cache
close dbWhat 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.
- "What happens if I forget try/finally around the yield?"
-
When the body raises, the exception is thrown into the generator at the
yieldline. With nofinally, the code after the yield never runs, so the cleanup is skipped and the exception then propagates. The run compares a manager without and withfinally.q25_nofinally.py (output)runs offlineopen -> raised open close -> raisedThe first manager printed
openand neverclose: the resource leaked. The second, withtry/finally, closed correctly.So the rule is to put release code in
finally. If you want to swallow an exception, catch it around theyieldand do not re-raise. Both patterns are visible in the code, and neither depends on the reader remembering what happens on error. - "Can a
@contextmanagerfunction be reused as a decorator?" -
Yes. A manager built with
@contextmanagercan be applied as a decorator, because the class that wraps the generator inherits fromcontextlib.ContextDecorator. For a class you write yourself, inherit fromContextDecoratorto get the same effect.@timer()then wraps the whole function body in thewith.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
withstatements. A generator-based manager can be entered only once: the second time the generator has finished, and you get aRuntimeError. 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?"
-
ExitStackhandles 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 offlineclosing c closing a raised: close failedThe callbacks run in the reverse order of registration, so
cgoes first. The failing one raises, anda, registered earlier, still runs. Only after all of them have run does the error reach the caller.Doing this by hand with nested
try/finallyis where bugs live: an error in one cleanup can skip the cleanups beneath it. That is whyExitStackexists, 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.
- The decorator:
@contextlib.asynccontextmanageron anasync defwithyieldandtry/finally, used withasync with. - Many resources:
contextlib.AsyncExitStackis the async twin ofExitStack. You can enter both sync and async managers, and the stack closes everything in reverse order, even if one cleanup fails. - 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
finallycan 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 withasyncio.shieldor keep it short. - The decorator:
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.
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])lz.real -> 1
__getattr__('missing') called
lz.missing -> computed-missing
__getattribute__('x')
Spy().x -> 10
Broken().foo -> RecursionError: maximum recursion depth exceededWhat 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__
def __getattribute__(self, n):
log(n)
return object.__getattribute__(
self, n)Runs only on failure
__getattr__
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__.
- "Why does
copy.copyorpicklebreak a naive proxy?" -
Both tools build the object without running
__init__.copy.copymakes an empty instance, then asks it for special names such as__setstate__or__deepcopy__. That empty instance has no_targetyet.Your
__getattr__is called for the missing special name. It readsself._target, which is also missing, so Python calls__getattr__("_target"), which readsself._targetagain, and so on untilRecursionError. Unpickling does the same dance, which is why a proxy that works in a quick test can crash only when it is cached withcopy, sent to another process, or stored withpickle.q26_proxy_copy.pyruns offlinenaive : RecursionError guarded: Guarded 1The guarded version raises
AttributeErrorat 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. Solen(proxy)fails withTypeError: object of type 'Proxy' has no len(), even though writingproxy.__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 usewrapt. 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 assignmentobj.x = v, including the ones inside__init__. It has the same trap as__getattribute__. Inside it,self.x = vcalls__setattr__again, forever.The way out is to call the base implementation:
super().__setattr__(name, value)orobject.__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 fordel obj.x.Frozen dataclasses show the pattern. Their generated
__setattr__raisesFrozenInstanceError, and their own__init__writes the fields withobject.__setattr__, the trickMoneyused 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 ofif 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.xon 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 toobject.__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
propertyor 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.
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()))limit=0 buggy: 10 | fixed: 0
falsy: [None, False, 0, 0.0, '', [], (), {}, set()]
__bool__ asked
Both -> False
__len__ asked
OnlyLen -> False
plain object -> TrueWhat 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?"
limit = limit or 10
if not coupon:
coupon = "NONE"
# 0 and "" are overwrittenExact
Say what you mean.
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.
- "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: returnis 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 ofNonemay mean "no filter", while[]may mean "match nothing". Thenottest 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 writeif not itemsorif len(items) == 0. And if neither fits, I write the comparison I mean, such asif 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)raisesValueError: 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 == 0and, for pandas,df.empty. For a one-element array,boolworks, 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
Moneyvalue returns true when the amount is non-zero. A result object returns true on success, asre.Matchdoes by beingNoneor an object.- Keep it cheap:
__bool__runs in everyif x:, so no I/O and no heavy work. - Return a real bool: returning
1or a string raisesTypeError. - 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. Thenlen(x)also works and invites wrong uses, andlist(x)or iteration code may be misled. Define__bool__alone, and if the meaning is surprising, skip it and let callers writex.is_valid. - Keep it cheap:
- "What is the bug with
x or defaultand a callable or datetime?" -
The trap is that
x or defaultreplaces any falsy value, not onlyNone. 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 offlineprice_bad(0) -> 9.99 price_ok(0) -> 0 price_bad(Decimal("0")) -> 9.99 price_ok(Decimal("0")) -> 0Here
price_badisprice or 9.99andprice_okisprice 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
orfor defaults only when every falsy value really should be replaced. Otherwise I write theis not Noneform.
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__.
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")))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.
def __str__(self):
return f"Order #{self.id}"
# [o] prints <Order object at 0x..>__repr__ first
Debug output is clear.
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.
- "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
evalon a repr from outside, because that is code execution on text. For round trips usejson,pickleorast.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.
- Dataclasses: mark the field
field(repr=False)and it disappears from the generated repr. - Pydantic: use
SecretStr; its repr andstrshow**********, and you call.get_secret_value()only where the value is needed. - 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 fromrepr(obj). - Dataclasses: mark the field
- "What does
!r,!sandformat()do?" -
They are three ways to ask an object for text inside an f-string.
{x!r}callsrepr(x),{x!s}callsstr(x), and{x:spec}callsformat(x, "spec"), which reachesx.__format__("spec"). Without any marker,{x}is the same asformat(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!sfalls back to the repr, while the plain{o}uses my__format__. The defaultobject.__format__only accepts an empty spec and then callsstr. Numbers and dates define their own spec languages, such as:.2fand:%Y-%m-%d.The
{n=}form (Python 3.8 and later) prints the expression text and then its repr, son='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 examplegetattr(self, "id", "?"). For parent-child links, print only the id of the other object. The standardreprlibmodule 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.
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)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 valueWhat 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.
sum([Points(1), Points(2)])
# TypeError: int + PointsWith start=
Give sum its own zero.
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.
- "Why does
sumnot just use the first element?" -
Because
sumhas 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.reducewithout an initial value does take the first element, and raises on an empty sequence.maxandmindo the same unless you givedefault=.q29_sum.pyruns offlinesum(["a", "b"]) -> unsupported operand type(s) for +: 'int' and 'str' max([]) -> max() iterable argument is empty max([], default=0) -> 0With a fixed start of
0, the first step is always0 + item, which is why a class needs__radd__or astart=value. In my own code I choose by the empty case: if "no items" has a natural answer (a zero total), I usesumwithstart=; if it is an error,reduceis fine. - "Does the same thing apply to
max,minandsorted?" -
Partly. They compare items instead of adding, so they need
__lt__(or akey=function) and no zero value.sortedandlist.sortneed only__lt__, whilemaxandminalso use the order operators between items.The empty case is the difference.
sorted([])returns[], butmax([])andmin([])raiseValueError: max() iterable argument is empty, because there is no sensible biggest of nothing. Passingdefault=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,Noneas 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
sumfine for floats?" -
Be careful with the claim. The error in
0.1 + 0.2 == 0.30000000000000004comes 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
sumadds on top is accumulation error: each running total is rounded.math.fsumavoids it and rounds only once at the end. Recent Python versions (3.12 on) already makesumof 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,
sumorfsumis fine. For money, never use floats at all. UseDecimalor integer cents (Q10). Also,sumrefuses 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,absandround?" -
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.
sum: define__radd__that accepts0, or tell callers to passstart=Money.zero(). I prefer the explicitstart=.abs: define__abs__. For a vector it is the length, for money the absolute amount.round: define__round__(self, ndigits=None). Return the same type whenndigitsis given.
The same idea covers
len(__len__),bool,hash,intandfloat(__int__,__float__), anddivmod.If the type should behave like a number, the
numbersmodule gives abstract bases that document the contract. If it needs the full set of comparisons, define__eq__and__lt__and addfunctools.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.
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)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 immutableWhat 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.
- "Why not subclass
tuple?" -
Subclassing
tuplegives 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 offlineTup((1, 2)) + Tup((3, 4)) -> (1, 2, 3, 4)For a Vector,
v + wmust add component by component, but the inherited+concatenates, and it returns a plaintuple, not your class. Slicing,in,count,indexand 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
_partstuple 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 asNamedTuple. - "Would you use a dataclass here?"
-
Yes, it is a fair shortcut. A
@dataclass(frozen=True)with one fieldcomponents: tuple[float, ...]generates__init__,__eq__,__hash__and__repr__. Frozen blocks assignment, and witheq=Trueandfrozen=Truethe 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, soVector((1, 2)), notVector(1, 2). To get the nicer call I would add a classmethod, or write__init__by hand. The generated repr showsVector(components=(1, 2)), which is accurate but wordy. Addingslots=Truesaves 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.5andnp.float64work?" -
The check
isinstance(k, (int, float))acceptsnp.float64, because that class inherits from Python'sfloat. It does not acceptnp.int64, which is not anintsubclass. A more general test isisinstance(k, numbers.Real), which both NumPy types satisfy through registration.q30_vector.pyruns offlineisinstance(np.int64(2), int) -> False isinstance(np.int64(2), numbers.Real) -> True isinstance(np.float64(2), float) -> TrueOperand order is the second trap. With a NumPy array on the left,
arr * vgets 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__ = Noneon your class tells NumPy to returnNotImplemented, so your reflected method runs once, on the whole array.q30_vector.pyruns offlinearray * W() -> ['rmul' 'rmul'] array * V() -> rmulI 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,
numpyarrays,fractions.Fractionordecimal.Decimalare 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.
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. 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 asproperty), call its__get__. It wins over the instance dictionary. - 2. Instance dictionary. If
obj.__dict__has the name, return that value. - 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.
__getattr__. If everything failed and the class defines__getattr__, call it. Otherwise raiseAttributeError.
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.
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) -> 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.
- "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
Basedefinesrate = 1andChild(Base)definesrate = 2, thenChild().rateis2becauseChildcomes first in the MRO. Writingchild.rate = 3creates 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.xprints 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 asobj.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.attron the class itself follows the same shape, one level up. The "type" of a class is its metaclass, usuallytype. 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. Fora.attrit is called as__get__(descr, a, A). ForA.attrit is called as__get__(descr, None, A), withNonefor the instance. A well-written descriptor checks for that and, when the instance isNone, 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.
classmethodbinds to the class in both cases, andpropertyaccessed 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.xon 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.
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)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 attributeWhat 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.
private int size;
public int getSize() {
return size;
}
// callers must write getSize()Python
Plain attribute now, property later.
class Box:
@property
def size(self):
return self._size
# callers still write box.sizeThe 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__.
- "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 offlinea.method -> instance value a.prop -> property a.prop = 1 -> property 'prop' of 'A' object has no setterHere I put an entry named
methodand one namedpropstraight 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 offlinea.m is a.m -> False a.m == a.m -> True a.m.__self__ is a -> True a.m.__func__ is A.m -> TrueTwo evaluations give two objects, so
issaysFalse, while==compares the pair (instance, function) and saysTrue. That matters when you register and later remove a callback. Compare with==or keep the one bound method in a variable, and never rely onis.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 atweakref.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.- Store the name: keep
name, and optionally"_" + nameas the storage key. - Use it in
__get__and__set__: read and writeobj.__dict__[self.name]orgetattr(obj, self.private), so one descriptor class serves any number of fields. - Use it in errors: messages such as
qty must be between 1 and 1000can 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 inCls.f = Ranged(...), does not get the call, so I call__set_name__by hand in that case. - Store the name: keep
- "Does
functools.cached_propertyuse this?" -
Yes.
functools.cached_propertyis 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.nameclears 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_cacheon 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.
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")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 differWhat 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.
class P:
def __init__(self, a):
self.a = a
p.extra = 1 # allowed__slots__
Fixed fields, smaller object.
class P:
__slots__ = ("a",)
def __init__(self, a):
self.a = a
p.extra = 1 # AttributeErrorThe 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.
- "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 offlineLoose has __dict__: True Tight has __dict__: False multiple bases have instance lay-out conflictLoosedid not declare slots, so it has a dictionary.Tightdeclares only its new nameband 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__")allowsweakref.ref(obj). Adding"__dict__"brings back a dictionary for undeclared names, on top of the fast declared slots.- Weak references: needed by
WeakValueDictionary,WeakSetand cache classes (Q15). Without"__weakref__"you getTypeError: cannot create weak reference to 'X' object. - 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. - 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. - Weak references: needed by
- "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
AttributeErrorinstead 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.copyandcopy.deepcopyuse the same machinery, so they work too.q33_pickle.pyruns offlineprotocol 0 TypeError a class that defines __slots__ without defining __getstate__ cannot be pickled protocol 2 ok 1 2 protocol 5 ok 1 2 copy: 2Protocol 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.
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)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, BWhat 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.
class D extends B implements C {
}
// state from one class only;
// default methods: pick onePython
Many parents, one MRO.
class D(B, C):
pass
# D.__mro__ gives a single
# deterministic search orderThe 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__.
- "Why is the diamond a problem in other languages?"
-
Without a rule, there are two problems. First, which version of a method wins when
BandCboth override one fromA? Second, doesA'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
AinsideD. You ask for a single shared copy withvirtualinheritance, 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
Ais searched after bothBandC, and a cooperativesuper()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 isinspect.getattr_static(obj, name), which finds the attribute without running descriptors or__getattr__.- Print the order:
[c.__name__ for c in type(obj).__mro__]. - Find the owner: loop over the MRO and check
name in vars(cls). The first hit is the winner for a normal method. - Check the instance: look in
vars(obj). An instance attribute can shadow a method (Q31). - 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)versusclass D(B, C)). A class in the middle forgot to callsuper(). Or an instance attribute has the same name as a method. The MRO list plus a quick look atvars(obj)finds all three. - Print the order:
- "Does the MRO apply to
__init__?" -
Yes,
__init__is an ordinary method, so the first__init__in the MRO runs. If it does not callsuper().__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 offlineby name : ['A', 'B', 'A', 'C'] super() : ['A', 'C', 'B']With names,
Aruns twice, once fromBand once fromC. That is a real bug ifA.__init__opens a resource or appends to a list. Withsuper(), 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
Handlerthat has aloggerand astoreis easier to test, because you can pass fakes. When I need polymorphism without a shared base, I use aProtocol(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.
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__])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.
class B extends A {
B() {
super(); // always A
}
}Python
super is the next in line.
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.
- "Why keyword-only arguments in the chain?"
-
Because the author of
Bdoes not know which class comes next in the MRO. For one object it may beC, 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 offlineD(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 callssuper().__init__(**kw). The star makesbkeyword-only, soD(1, 2)cannot put a number into the wrong slot. The extra**kwcarries 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 raisesTypeErrorif anything is left. In the demo above,D(bb=1)failed withobject.__init__() takes exactly one argument (the instance to initialize).That is a feature. A mistyped keyword such as
bbforbis caught at once, rather than silently ignored. Without the end-of-chain check, every**kwwould 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 callsuper().__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 thanobjectdoes. - "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 assuper(__class__, self).q35_cell.pyruns offline('__class__',) <class '__main__.Child'> baseThe cell holds
Child, the class that owns the method. Starting from there,super()finds the next class after it intype(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 thensuper()reachesBase.Take a
LoggingMixin.handlethat logs, callssuper().handle(req), and logs the result. Put it on any handler class and you get logging around everyhandlewithout 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.
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)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 = 1What 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.
class Foo extends Base {
int x;
}
// class loaded by ClassLoader;
// no code runs "as" class bodyPython
The class statement is code.
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.
- "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:
- 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.
abc.ABCMeta: tracks abstract methods and letsisinstanceaccept registered "virtual" subclasses.- Enums:
EnumTypemakesColor.REDa member with a name and value, and rejects duplicate names. - 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 offlinemetaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases M2Baseuses my metaclassM,abc.ABCusesABCMeta, and neither is a subclass of the other, soBothfails. The fix in the second half is a combined metaclassM2(M, abc.ABCMeta), passed withmetaclass=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,floatortuplesubclass is immutable, so__init__comes too late to change the value. For example, aCelsius(float)that rejects values below absolute zero, or that rounds, must do so in__new__beforefloat.__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, andMeta.__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
OrderedDictfrom__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 twodef totalor twox = 1in one body is an error rather than a silent overwrite. The standardenummodule 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.
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)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 basesWhat 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.
// reflection or ServiceLoader
// finds implementations
for (var p : ServiceLoader
.load(Plugin.class)) { ... }Python
The base class hears about it.
class Plugin:
registry = {}
def __init_subclass__(cls, **kw):
Plugin.registry[cls.__name__] = clsThe 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.
- "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.
- Import the package at start-up: walk the plugins folder with
pkgutil.iter_modulesand callimportlib.import_modulefor each, so the discovery step is visible in one place. - Use entry points: an installed package declares
[project.entry-points."pricer.plugins"]in its metadata. The host callsimportlib.metadata.entry_points(group="pricer.plugins")and loads each one. This finds plugins from other packages without importing them first. - 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.
- Import the package at start-up: walk the plugins folder with
- "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 sayclass Base2(Plugin, register=False). The hook returns early whenregisteris 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 useABC. I ran a check inside the hook:Mid(P), which adds nothing, reported abstract, andLeaf(P), which implementsf, reported not abstract ({'Mid': True, 'Leaf': False}, same on 3.12 and 3.14). That order of events is an implementation detail ofABCMeta, 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 offlineregistry: ['csv'] Bad must define keyCsvdeclares akeyand registers.Midopts out withregister=False.Badforgets 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
Pluginis 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".
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")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 machineWhat 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.
@dataclass(frozen=True, slots=True)
class Order:
id: int
qty: intBoundary
Validate untrusted input once.
class OrderIn(BaseModel):
id: int
qty: int = Field(gt=0)
# parse JSON -> OrderIn -> OrderThe 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.
- "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_setattrhooks that validate on later assignments, and more control over equality, hashing and the repr. It also has the modernattrs.definestyle, 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__andfield()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 offlineNamedTuple Point == Offset : True NamedTuple Point == (1, 2) : True dataclass P2 == O2 : False dataclass P2 == (1, 2) : FalseThat equality can be a bug. A
Point(1, 2)equals anOffset(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 fromcsvor 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.
- To a dict:
dataclasses.asdict(obj),obj._asdict()for a NamedTuple,attrs.asdict(obj), andmodel.model_dump()for Pydantic. - From a dict:
Cls(**data)for dataclasses and attrs,Point(**data)for NamedTuple, andModel.model_validate(data)for Pydantic, which also checks the types. - 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
asdictcopies nested dataclasses recursively, which can be slow on big structures, and thatmodel_dump()needsmode="json"when you want types such asdatetimeturned 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.
- To a dict:
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.
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")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'] <- leakedWhat 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.
def __init__(self, codes=[]):
self.codes = codes
# silent shared statedataclass
Refused at import.
codes: list = field(
default_factory=list)
# fresh list per instanceThe 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.
- "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__toNone(Q22).q39_defaults.pyruns offlineBox.__hash__ -> None mutable default <class '__main__.Box'> for field b is not allowed: use default_factoryThe 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, usedefault_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 fieldfield(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=Falseis left out of the constructor, so it may follow fields that have defaults. Withfrozen=True, a plain assignment inside__post_init__raises, so writeobject.__setattr__(self, "total", ...)as in Q10, or avoid storing the value and offer a@propertyinstead.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_factorycannot 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_factoryis called inside the generated__init__each time an instance is created, whatever the class options are. Sofrozen=Trueandslots=Truedo 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=Truethe 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-argumentsuper()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 atupleorfrozensetfield. - "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 andfield(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.
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)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 5000What 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.
@property
def qty(self): return self._q
@qty.setter
def qty(self, v):
if v < 1: raise ValueError
self._q = vOne descriptor
Declare the rule once.
class Order:
qty = Ranged(int, 1, 1000)
class Product:
qty = Ranged(int, 0)
# rule lives in one classThe 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.
- "Does the descriptor work with
__slots__?" -
Not as written. The descriptor stores its value in the instance as
_qtythroughsetattrorobj.__dict__. A slotted class has no__dict__, and a name that is not declared in__slots__raisesAttributeError.- 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. - Keep values inside the descriptor: a
WeakKeyDictionarykeyed by the instance. It needs no slot, but requires"__weakref__"in the slots, hides state away from the object, and breakscopyandpickle.
I choose the first. State that lives in the object is visible in
reprand survives copying and pickling, and the per-model cost is one line. A name clash is another trap: a slot calledqtycannot also be the descriptor. That is why the stored name has a leading underscore. - Add the private name to the slots:
- "Why return
selfwhenobj is None?" -
When you access
Order.qtyon the class, Python calls__get__(None, Order), soobjisNone. If the method ran its normal path, it would try to read the stored value fromNoneand crash with anAttributeError.Returning the descriptor itself in that case has real uses. You can inspect the rule, as in
Order.qty.highorOrder.qty.low, which a form generator or documentation tool can read.help(Order)andinspectdo 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 ofproperty, 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=Noneis 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.
- Good values: a normal value, and exact boundaries equal to
lowandhigh, which are the usual off-by-one spots. - Bad values: one below the low bound, one above the high bound, and a wrong type such as
"5"or5.0for an int field. - Edge types:
Truefor anintfield. In Pythonboolis a subclass ofint, so anisinstancecheck accepts it unless you reject it explicitly. - 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.
- Good values: a normal value, and exact boundaries equal to
- "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
lowandhighin 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 withobject.__setattr__or sets_qtydirectly.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.
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.
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()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 | 10What 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.
class Counter {
int x = 10;
void bump() { x += 1; }
}
// x is a field: explicitPython
Assignment decides the scope.
x = 10
def bump():
x += 1
# UnboundLocalError:
# x is local in bumpThe 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.
- "Why not let Python fall back to the global?"
-
Because then one line would mean two different things depending on the run. If
x += 1read the globalxwhen no local existed and created a local after that, the same name would switch scope in the middle of a function. Nobody could say whichxa 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_FASTwith 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
globalandnonlocal(Q42) when you do want to rebind an outer name. The error is also a gift in disguise:UnboundLocalErrortells you exactly that the name is local here, and nothing has set it yet. - "Do loops and
ifblocks 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,withortry. A loop variable stays alive after the loop, and a name assigned inside anifexists after it if that branch ran.q41_scopes.pyruns offlineloop variable after loop: 2 comprehension leaks j? : FalseThe loop variable
isurvives (the value is 2), but the comprehension variablejdid 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
UnboundLocalErrorwhen the branch did not run. And a loop variable reused later holds the last value, so afterfor t in tenantsthe nametstill 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
xin a method cannot find a class attributex. You must writeself.xorClassName.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, withx = 5in the class, failed withNameError: 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.RATEorPricer.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 laterlist(...)in that module finds your variable and fails.q41_scopes.pyruns offlinelist(...) after list=[..]: 'list' object is not callableThe 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 callsid(x)ormax(...).The usual victims are
list,dict,set,str,id,type,input,max,min,sum,filterandformat. Linters catch this: Ruff has rules A001 and A002 for variables and arguments that shadow built-ins. My habit is to name thingsitems,order_idorkindrather thanlist,idandtype.
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.
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)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.
- "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
monkeypatchso that changes are undone automatically after each test. - "What does
globalhave to do with threads?" -
The line
calls += 1looks 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
nonlocalrejecting if I mistype?" -
It refuses to create a name.
nonlocal ntells Python thatnbelongs 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 offlineno binding for nonlocal 'n' found 1The first line is the error message, and the second is
globalcreating a variable at the module level, with no complaint. That makes typos loud fornonlocaland silent forglobal: if you writeglobal totland assign it, you now have a new module variabletotlnext to the originaltotal, and no error until much later.The check also means
nonlocalcannot reach the module level. It looks only at enclosing function scopes. For module-level variables, you needglobal.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.
- 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.
- Configuration: a frozen settings object, created once at start-up and read everywhere. Nobody can rebind it, so nobody can surprise anyone else.
- Caches:
functools.cacheon a pure function, or a cache object passed in, so it can be sized, cleared and replaced in tests. - 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.2read by many functions never changes. The smell is a module-level variable that functions rebind withglobal.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.
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])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.
for (String t : tenants) {
tasks.add(() -> reprice(t));
}
// each t is a new final valuePython
Capture the variable itself.
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.
- "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-eachloop 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: infor t in tenantsthere is only onet, 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 offlinelambda: t -> ['c', 'c', 'c'] lambda t=t: t -> ['a', 'b', 'c']The second line shows the default-argument fix,
lambda t=t: t, which evaluatestat 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_laterand 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 offlineextra argument -> oops partial(upper,t) -> ['A', 'B', 'C'] pickle a lambda -> PicklingError pickle a partial -> TrueThe 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. Apartialstores 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,.argsand.keywordsshow what was bound. And they can be pickled when the function is a module-level one, while a lambda cannot, which matters formultiprocessing, as the last two lines of the demo show.The default-argument trick is fine for a quick script. In shared code I use
partialor a small factory function. - "How would you catch this in review?"
-
I look for a
lambdaor an innerdefcreated 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.
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)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: TrueWhat 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.
@Transactional
public void save() { ... }
// stored in the class file;
// a framework reads it laterPython
Decorator is code that runs.
@transactional
def save(): ...
# save = transactional(save)
# runs now, replaces the functionThe 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.
- "Does the decorator run for every call?"
-
No. The decorator function runs once per decorated function, when the
defstatement is executed. Only the wrapper it returns runs on each call. The demo shows both moments.q44_when.pyruns offlinebefore def decorating price after def calling price calling price"decorating price" appears once, between the two
printlines 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.
@dataclassand@functools.total_orderingwork 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 withdef wrapper(*args, **kwargs)passesselfalong without any special handling.@staticmethod,@classmethodand@propertyare decorators too, and they return descriptor objects (Q32). That is why their order against your own decorator matters. Put@propertyon 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
selfis 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.wrapsdoes 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
BufferedReaderaround 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.
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")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 lostWhat 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".
def deco(func):
def wrapper(*a, **k):
return func(*a, **k)
return wrapperWith wraps
Metadata survives.
def deco(func):
@wraps(func)
def wrapper(*a, **k):
return func(*a, **k)
return wrapperThe 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__.
- "What does
__wrapped__give me?" -
functools.wrapssetswrapper.__wrapped__ = func, a direct link to the function that was decorated.inspect.signaturefollows it, so tools show the original parameters. A test can callprice.__wrapped__(3)to run the undecorated logic without the extra behaviour.q45_unwrap.pyruns offlineprice.__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__ -> wTwo stacked decorators with
wrapsmake a chain.inspect.unwrap(f)follows it to the end, and manualf.__wrapped__.__wrapped__does the same one step at a time.The last two lines show what happens when one decorator,
plain, does not usewraps. The chain is broken at that layer, and both lookups stop at the wrapper namedw. One careless decorator is enough to hide everything below it from tools. That is why I makewrapsa rule for every decorator. - "Does
wrapsfix type checkers?" -
No.
wrapsfixes run-time metadata and nothing else. A type checker does not run your code, so it never sees the effect ofwraps. For static typing, the wrapper's signature must be written withParamSpecandTypeVarso 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 isAny, 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 andhelp(). Annotations withCallable[P, R]andParamSpecserve the type checkers. Neither can replace the other. - "What breaks with
async deffunctions?" -
A plain wrapper around an
async deffunction 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 offlinesync wrapper measured 0.002 ms async wrapper measured 100 msThe function sleeps for 0.1 s, and the synchronous timer reports a few microseconds. A
try/exceptin 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 wrapperthat awaits the call. To support both kinds with one decorator, checkinspect.iscoroutinefunction(func)at decoration time and return the matching wrapper.wrapsworks 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, andinspect.signature(decorated) == inspect.signature(original).- Identity: name, docstring and module are those of the original function, not
wrapper. - Signature: the parameters seen by
inspect.signaturematch, including defaults and annotations. - 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 adef wrappernot 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. - Identity: name, docstring and module are those of the original function, not
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.
- Outer:
retry(times)receives the configuration and returns the decorator. It runs once, at definition time. - Middle:
decorator(func)receives the function and returns the wrapper. It also runs once, right after. - Inner:
wrapper(*args, **kwargs)runs on every call, usingtimesandfuncfrom 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.
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) 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.
@Retryable(maxAttempts = 3)
public String call() { ... }
// framework proxies the beanPython
A factory returns the decorator.
@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.
- "How can
@retryand@retry(times=3)both work?" -
Make the function a parameter that defaults to
None, and make the options keyword-only. Whenfuncis given, you were used bare (@retry), so decorate it directly. When it isNone, you were called with options (@retry(times=5)), so return a decorator that waits for the function.retry_both.pyruns offlinedef 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 wrapperThe star before
timesmatters. It stops@retry(3)from putting3into thefuncslot and turning the call into nonsense, so a mistake fails clearly.I tested both forms, and they print
times = 3andtimes = 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 differenttimesdo not interfere.q46_closure.pyruns offline('func', 'times') [<function flaky at 0x79d98667ade0>, 4] flakyThe 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
nonlocalinside 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()orstats(), andisinstance(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 withfunctools.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
isinstancechecks, 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 fakesleepthat records its arguments and returns at once, and a fake random source, so the test runs in milliseconds and the same way every time.- Fake the function: a function that raises
ConnectionErrora known number of times, then returns a value. - Count the calls: with
times=3and a function that fails twice, assert it was called exactly 3 times and the result is the final value. - Check the delays: the fake
sleepwas called with the expected, capped values. - Check the failure path: a function that always fails raises the last exception after
timesattempts, and aTypeError(not retryable) is raised on the first call.
Q48 shows a version with injectable
sleepandrngarguments, written for exactly this. A test that really sleeps for two seconds will be skipped by tired developers sooner or later. - Fake the function: a function that raises
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.
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())--- 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: doneWhat 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.
@Order(1) class Auth { ... }
@Order(2) class Cache { ... }
// priority lives in numbers,
// far from the methodPython
Order is the line order.
@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.
- "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 offlinecache above check, anonymous caller : 2 check above cache, anonymous caller : deniedWith
@cacheabove@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.
@retryabove@timeout(2)gives each attempt two seconds, so three attempts can take six.@timeout(2)above@retrycaps 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
@propertyand@lru_cache?" -
@propertymust be the outermost, because it needs a function to turn into a descriptor. Putting@lru_cacheon the outside fails, since apropertyobject is not a function.q47_prop.pyruns offline1 TypeError: Expected first argument to be an integer, a callable, or NoneThe working order,
@propertyabove@lru_cache, runs but has the leak from Q50: the cache key includesself, so every instance stays in the cache and is never freed. It also gives each lookup a hash ofself, 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 withf.__wrapped__, thenf.__wrapped__.__wrapped__. Each decorator that usedfunctools.wrapsadds 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_filenameand__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 requirewrapseverywhere (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 offlineregister above dataclass keeps final class : True register below dataclass keeps final class : Falseregisterabove the dataclass sees the final class.registerbelow 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_orderingchecks 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.
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:]]) 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.
for _ in range(3):
try: return call()
except Exception: sleep(1)Backoff plus jitter
Spread out, capped.
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.
- "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 offlineattempt 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 sWith 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
ParamSpecchange for callers?" -
It lets the type checker keep the exact parameters of the decorated function.
ParamSpec(namedP) captures "whatever parameters the function has", andCallable[P, R]says the wrapper takes the same ones and returns the same typeR. A checker such as mypy or pyright then rejectsfetch_rate(5)if the original isdef fetch_rate(currency: str) -> float, andreveal_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 isAny, so the checker stops helping on the functions that matter most.Two rules:
P.argsandP.kwargsmust be used together, as*args: P.args, **kwargs: P.kwargs, and the wrapper is annotated to returnR.Concatenate(Q121) adds or removes a leading parameter. AndParamSpecchanges nothing at run time, sowrapsis still needed. - "What about async functions?"
-
You need a separate version. A synchronous wrapper around an
async deffunction would return the coroutine at once, unawaited, so nothing is retried: the failure happens later, in the caller, outside yourtryblock (Q45).The async version is
async def wrapper(...), withresult = await func(*args, **kwargs)inside the retry loop, andawait asyncio.sleep(delay)between attempts. A blockingtime.sleepin 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
tenacityorbackoff. 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.
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())orders.route = /orders | still the original function: Api.orders
prices has route? False | prices is wrapper? True
scanned routes: {'/orders': 'orders'}
[timed] before call
pricesWhat 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.
@GetMapping("/orders")
List<Order> orders() { ... }
// stored in class file;
// Spring scans and wires itPython
Code that runs and may replace.
@app.get("/orders")
def orders(): ...
# runs now: registers orders,
# returns the functionThe 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.
- "Does Python have something closer to Java annotations?"
-
Yes, in three forms. First, type annotations.
x: intstores 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 decosets an attribute and returns the same function. A framework scans forroutelater, 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.
- 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. - Order surprises: stacked decorators apply bottom-up and interact (Q47).
- Broken introspection: without
wraps, names, docstrings and signatures are lost (Q45). - Typing cost: without
ParamSpec, the decorated function becomesCallable[..., 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.
- Hidden control flow: a retry, a cache, a transaction or a permission check is invisible at the call site. Someone reading
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.
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())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.
class Svc:
@lru_cache(maxsize=None)
def rate(self, cur):
return fetch(cur)Fixed
Cache values, not instances.
@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.
- "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=8192cache holds all of them with room to spare.cache sizingruns offline8192 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,maxsizeandcurrsize. 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=Nonewhen 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)orfrozenset(items), or to cache a small function that takes the tuple.q50_cache.pyruns offlinecache_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: 2The second part of the output is about equal values of different types.
1and1.0are equal and hash the same, sotwo(1, 2)andtwo(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, usetyped=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_cachethread-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 putlru_cacheon anasync deffunction, it caches the coroutine object, which can be awaited only once. The second caller getsRuntimeError: 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
functoolsare 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_cachehas no expiry. It has onlycache_clear(), which empties everything, and in recent versionscache_parameters()to read its settings. If results go stale, such as exchange rates that change hourly, you need a policy.- 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. - Put a time bucket in the key: pass
int(time.time()) // 3600as an argument, so a new hour is a new key and old entries age out through the LRU limit. - Use a TTL cache:
cachetools.TTLCacheexpires 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.
- Clear on a schedule: a background job calls
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.
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)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 NoneWhat 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.
def f():
x = 1
return x
# x is gone after returnGenerator
Frame is suspended.
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.
- "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
withblock, a database cursor or a lock.The trap is a generator you stop reading half-way. The
withinside 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()orcontextlib.closing(gen). That raisesGeneratorExitat the pausedyield, and thewithblock 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 defcoroutine is also a function whose frame can be suspended and resumed.awaitplays the role ofyield: it pauses the frame and hands control back to whoever is driving it. Here the driver is the event loop, not aforloop.- Pause: the coroutine reaches
awaiton something that is not ready, and its frame is suspended with all its locals. - Wait: the event loop runs other tasks while the result is pending.
- 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. - Pause: the coroutine reaches
- "What does
return valuedo in a generator?" -
It ends the generator and carries a final value out, attached to the
StopIterationexception ase.value. Aforloop catchesStopIterationsilently 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 fromreceives it as the value of the expression, soresult = yield from sub()gets whateversubreturned (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
returngivesNone. And in anasyncgenerator,return valueis 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.
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()):,}")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 differWhat 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.
lines = open(f).readlines()
rows = [parse(l) for l in lines]
# 20 GB file -> MemoryErrorPipeline
Memory stays flat.
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.
- "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
tracemallocswitched on, so a little pessimistic).time estimateruns offline20,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.
- Only the top N: keep a heap of size N and drop the rest. Memory is N entries, whatever the input size.
- 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.
- 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 raisingUnicodeDecodeError.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.
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]))) 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.
- "Why not just use a for loop?"
-
For plain iteration, you can.
for x in sub: yield xandyield from subgive the same items, andyield fromis 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 fromdoes. It forwardssend()values straight into the sub-generator. It forwardsthrow()andclose()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
tryaround everyyield, special handling ofGeneratorExit, and a manual catch ofStopIterationto fetch the result. Almost everyone gets one of those wrong. So I use a plain loop when I only read values, andyield fromthe 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 fromchains 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 fromaccept any iterable?" -
Yes, any iterable.
yield fromcallsiter()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 receivessendandthrowcalls through it; for the others it just iterates.That makes it handy for combining sources inside one generator:
sources.pydef 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 timeThis 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, writeyield "abc". The same goes for a dict, which yields its keys, not its pairs. - "What replaced
yield fromfor coroutines?" -
The answer is
await. Before Python 3.5, coroutines were generators decorated with@asyncio.coroutineand written withyield from. The 3.5 syntaxasync defandawaitreplaced 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 fromdoes 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
awaitis only legal insideasync def, so you cannot accidentally mix up the two. This also explains the rule that you cannot callawaitfrom 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.
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")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
closedWhat 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.
- "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 firstnext()runs the body up to the firstyield, and only then is there somewhere to put a value.That is why the first call must carry no payload:
next(g)org.send(None). Sending a real value to an unstarted generator raisesTypeError, with a message saying you can only sendNoneto a just-started generator.- Create:
g = averager()builds the object; nothing runs yet. - Prime:
next(g)runs to the firstyieldand stops. - Use: now
g.send(10)delivers 10 to that pausedyieldand returns the next yielded value.
Older coroutine code hid step two behind a small decorator. Today I just call
nextonce, with a comment. - Create:
- "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 raisesGeneratorExitat the pausedyield, and thefinallyblocks andwithexits 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
asyncgenerator, 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(oraclosingfor 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/awaitreplaced coroutines built from generators, sosendis no longer how most people write concurrent code.Where it survives:
- send: running accumulators, push-style parsers and simulations, where a generator keeps state between values you push in.
- throw:
contextlib.contextmanager. When the body of yourwithblock raises, the library callsthrow()on the generator, so the exception appears at theyieldand yourtry/finallyorexceptthere can handle it (Q25). - 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
sendmyself: a small running-average generator. - "Can I get the return value after close?"
-
Yes, since Python 3.13, and only if the generator catches
GeneratorExitand then returns a value. In 3.12 and earlierclose()always returnedNone. Here is the same script on both versions:q54_close_value.pyruns offlinedef 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())output3.12: close() returned: None 3.14: close() returned: 12So the generator catches
GeneratorExit, whichclose()raises at the pausedyield, 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.valueoryield 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(...).
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")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 differWhat 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.
total = sum([x * x for x in nums])
# list of N squares existsLazy
One item at a time.
total = sum(x * x for x in nums)
# no list at allThe 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.
- "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 bindingn = 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
anyandall?" -
They are the best use of the lazy form, because both stop as soon as the answer is known.
anyreturnsTrueat the first truthy item.allreturnsFalseat 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:
- Generator:
any(x > 100 for x in data)tests one item, returnsTrue, and builds nothing. - List:
any([x > 100 for x in data])first tests all million items and builds a million-element list of booleans, and only thenanylooks 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. - Generator:
- "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 istuple(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.
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])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.
by = defaultdict(list)
for k, v in rows:
by[k].append(v)groupby
Only neighbours.
for k, g in groupby(rows, key):
use(k, list(g))
# needs sorted inputThe 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.
- "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, sogroupbyis 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 bygroupbyon the same key. Together they group many large sorted files without loading any of them.The rule I apply in review:
groupbyis fine when a comment or a visiblesortedorORDER BYshows 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:
- defaultdict(list): one pass, O(n) time, but it still holds every item, just grouped.
- 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.
- 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 offlineunsorted: [('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 groupsgroups = {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))} # correctThe 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
groupbymust have a visiblesorted(...)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.
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), "...")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.
for i in range(0, len(xs), 100):
chunk = xs[i:i + 100]
save(chunk) # xs must be a listitertools
Any iterable.
for chunk in batched(rows, 100):
save(chunk) # rows can be a streamThe 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.
- "What was there before
batched?" -
People wrote a small helper, usually with
islice. The common one-liner wasiter(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 astrict=Trueoption 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 batchBatching 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
islicenot 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
isliceto 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.pyfrom 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
accumulatediffer fromreduce?" -
The difference is what you get back.
functools.reducefolds a sequence into one final value.itertools.accumulateyields 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,
accumulategives 100, 70, 120, andreducewith addition gives only 120. If I want the total alone, I would writesum(amounts). It is clearer and faster thanreducefor addition. I usereduceonly for folds thatsum,min,maxormath.prodcannot do, such as merging a list of dictionaries.Both take a function, and
accumulatehas aninitial=option (3.8+) to start from a value and emit it first. Becauseaccumulateis lazy, it works on streams: you can write each running balance to a file without holding the series. - "When is
teeacceptable?" -
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.
teeonly 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,
teeholds 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.- Lockstep consumers: use
tee; the buffer stays tiny. - Independent or slow consumer: write the data once to a list or a file, or run the pipeline twice from the source.
- 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.
- Lockstep consumers: use
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.
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))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.
var out = source.stream()
.map(n -> n * 2)
.filter(n -> n > 2)
.toList(); // terminal op runs itPython
Generators.
out = [n for n in
(n * 2 for n in source)
if n > 2] # list() pullsThe 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.
- "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(ormultiprocessing), 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'sInterpreterPoolExecutoris 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.
- 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 consumingforloop. The generator that raised is finished, and laternext()calls on it giveStopIteration. - 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 awith contextlib.closing(...)block. In Java, a stream backed by a resource, such asFiles.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.
- Python: the exception is raised inside the stage that failed. It propagates out of that generator's
- "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, anditertools.islicestop early in the same way.Java has direct equivalents:
findFirst,limit,anyMatch,allMatchandnoneMatch. A pipeline offilterandmapfollowed byfindFirstprocesses 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 fullListin 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, orFiles.linesin 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.pylines = 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
toolzandmore-itertoolsadd 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.
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))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 7What 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.
def to_json(v):
if isinstance(v, Decimal):
return f"{v:.2f}"
elif isinstance(v, date): ...singledispatch
Register per type.
@to_json.register
def _(v: Decimal):
return f"{v:.2f}"
# new types add themselvesThe 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.
- "What is the difference between
cacheandlru_cache?" -
The only difference is the size limit.
functools.cache(f)is the same aslru_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_cacheand checkcache_info()for the hit rate, because a cache with a poor hit rate costs memory and gives nothing back. - "Does
cached_propertywork with threads?" -
Mostly yes, with one change you should know about.
cached_propertystores 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
partialrather than a lambda?" -
Mainly because of three practical differences. A
partialobject can be inspected, it can be pickled, and it does not have the late-binding trap.- Introspectable:
p.func,p.argsandp.keywordsshow what it wraps, which helps in logs and tests. - Picklable: a
partialof a module-level function can be sent to a worker process (Q73). A lambda cannot be pickled by name. - Binds now: the arguments are captured when you create it. A lambda such as
lambda: reprice(tenant)looks uptenantwhen 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
partialhas no__name__, so a logger that printsfn.__name__fails. Usefunctools.update_wrapperto copy the name across, or logp.func.__name__. - Introspectable:
- "Does singledispatch work on methods or on second arguments?"
-
Not directly, on both counts.
singledispatchpicks the implementation from the type of the first positional argument, and nothing else. On an instance method, the first argument isself, 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 afterself. For dispatch on two arguments, you have three honest options: a dictionary keyed by a tuple of types, a small chain ofmatchstatements with class patterns, or the third-partymultipledispatchpackage.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
Numberwould coverintandfloatthrough the abstract-class hierarchy. That makes it a clean replacement for anisinstanceladder, 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.
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)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.
def all_orders(api):
out = []
while cursor is not None:
out += page(api, cursor)
return outLazy
Fetch pages on demand.
def iter_orders(api):
while True:
items, cur = page(api, cur)
yield from itemsThe 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.
- "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_cursorand 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 publiccursorattribute that updates after each page. The caller readsit.cursorat 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.- Laziness: creating the iterator makes zero requests, and the first
nextmakes exactly one. - Partial use: taking 3 items from a page of 100 makes one request, not more.
- Retries: a transient failure is retried and the sleeps follow the expected backoff, while a 400 is not retried.
- 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 offlinerequests before first next: 0 [1, 2, 3, 4] requests so far: 2 - Laziness: creating the iterator makes zero requests, and the first
- "Async version?"
-
Yes, and the structure is the same. Use an
async defgenerator, which hasyieldinside, and consume it withasync for. Each page request becomes an awaited call, and the retry delay usesawait asyncio.sleep(...)instead oftime.sleep, which would block the whole event loop.Three things deserve care. First, cleanup: an async generator's
finallyblock needs the event loop to run, so abandoning it half-way is riskier than with a normal generator. Wrap it incontextlib.aclosing, so the session is closed when the consumer stops early, whether bybreakor 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 withasyncio.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.
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.
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}")__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 differWhat 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.
java -jar app.jar
JVM starts (~40 ms)
loads classes lazily
main() runsPython
Interpreter, site, then compile.
python app.py
runtime + site (~20 ms)
compile app.py to bytecode
__main__ runsThe 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.
- "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 runsimport random, the finder checks your folder first, finds yourrandom.py, and stops. The real one is never reached.The damage spreads past your own code. Libraries that import
randominternally get your file too, and they fail in confusing ways, often with a message about a "partially initialised module" or a missing attribute such asrandom.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, printmodule.__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
.pthfile, and why mention it?" -
A
.pthfile is a plain text file insite-packages. When thesitemodule runs at start-up, it reads each one. Every line that is a directory path is added tosys.path, and every line starting withimportis 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, includingpython --versionstyle tiny scripts, and is easy to forget.To find the cause of a slow start, split the problem:
- Skip site:
python -S -c passstarts without it. If that is much faster, the cost is insiteor.pthfiles. - See imports:
python -X importtime -c passlists what was imported and how long each took. - Look inside: open the
.pthfiles insite-packagesand read theimportlines.
- Skip site:
- "How do
python -m pkgandpython script.pydiffer?" -
The difference is what goes first on the path and whether the file is treated as part of a package.
- 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 asfrom . import utilfails. - 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
-mfor anything that lives inside a package.python -m pytestandpython -m uvicorn app.main:appthen import the same way every time, whichever directory you started from. - python script.py:
- "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:
- Import less at start: do not import a heavy library in a module that every command loads.
- Import lazily: move heavy imports inside the function that needs them, or use
lazy importin 3.15 (Q74). - No work at import time: no file reads, network calls or big table builds at module level.
- Keep the cache writable: so
.pycfiles 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.
import dis
def price(qty, unit, rush=False):
total = qty * unit
if rush:
total += 5
return total
dis.dis(price) 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_VALUEWhat 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.
total = qty * unit
if rush:
total += 5
return totalBytecode
What the VM runs.
LOAD qty, unit
BINARY_OP *
STORE total
LOAD rush; JUMP_IF_FALSE
LOAD total, 5; BINARY_OP +=
RETURN totalThe 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.
- "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_OPjust 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
disoutput 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 betweenjavap -canddis. - "What is
RESUMEat the top?" -
RESUMEis 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 asLOAD_ATTRorCALL, 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.dishides them by default and shows them withshow_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
disin 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:
- Folding: does
60 * 60 * 24compute at run time?disshows a singleLOAD_CONST 86400, so no. - Atomicity: is
x += 1one step? It is several instructions (load, add, store), which is why threads can interleave in it (Q78). - Scopes: does a comprehension have its own frame? Not since 3.12, because it is inlined.
- Errors: why does
UnboundLocalErrorhappen? The function usesLOAD_FASTfor 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).
- Folding: does
- "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
.pycfiles 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
.pycfiles 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.
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)")--- 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.
interpret -> profile
hot method -> machine code
(C1, C2 compilers)Python
Hot instructions rewritten.
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.
- "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:
- Arithmetic and comparison:
BINARY_OPandCOMPARE_OPfor ints, floats and strings. - Attribute and name lookup:
LOAD_ATTRfor instance attributes, slots, class attributes, modules and properties, plusLOAD_GLOBALfor globals and builtins, andSTORE_ATTR. - Calls:
CALLfor Python functions, builtins and methods. - Loops and indexing:
FOR_ITERover lists, tuples and ranges, andBINARY_SUBSCRon 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. - Arithmetic and comparison:
- "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:
- Same types: keep hot functions monomorphic where it is natural, and convert at the edge.
- 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.
- Specialisation: default, no switch, safe to rely on.
- 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.
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)") 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.
javac Svc.java -> Svc.class
(done before deploy)Python
Compile on first import.
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.
- "Should I commit
.pycfiles or__pycache__?" -
No. Add
__pycache__/and*.pycto.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 incpython-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 clonegives every file a new time, so the committed.pycwould be rejected as stale anyway. You carry noise and gain nothing.The exception is deliberate: a pre-compiled, hash-based
.pycin 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
.pycmake the program faster?" -
It makes start-up faster, and it does not make running code faster. The
.pycfile 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:
- Pre-compile at build time: run
python -m compileallin the image build step, before the filesystem becomes read-only. The.pycfiles are then already there and are reused. - Redirect the cache: set
PYTHONPYCACHEPREFIXto 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/tmpis lost when the container restarts, so for repeated starts the build-time option is better. - Pre-compile at build time: run
- "How do reproducible builds use hash-based pycs?"
-
A normal timestamp-based
.pycheader contains the source file's modification time. The same source built on two machines, or on two days, therefore produces different.pycbytes, 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:
- Checked: at import, Python re-hashes the source and compares. It is safe if the source changes, at a small cost.
- 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(orunchecked-hash). The environment variableSOURCE_DATE_EPOCHgives 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.
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])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.
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.
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.
- "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.
- Explicit stack: for trees and graphs, keep a list of nodes still to visit:
stack = [root], thenwhile stack: node = stack.pop(), and push the children. Depth is limited by memory, not by the recursion limit. - Loops for linear definitions: a factorial or a sum over a chain is a
forloop. - Folds:
functools.reduceoritertools.accumulatereplace recursion that combines items one by one. - Memoise overlapping subproblems:
lru_cacheavoids 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.
- Explicit stack: for trees and graphs, keep a list of nodes still to visit:
- "Does the JSON module or
picklehave recursion issues?" -
Yes. A deeply nested input makes the parser recurse, and past the limit it raises
RecursionError. The standardjsonmodule in pure-Python mode, andpickle, 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.loadsdata 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
musttailsupport (in recent Clang versions) so the interpreter's own instruction handlers jump to each other instead of going through one bigswitch. 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.
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]})")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, noisyWhat 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.
HotSpot: interpret, profile,
compile hot code with C1/C2
always on, tuned by flagsPython
JIT is an opt-in extra.
PYTHON_JIT=1 python app.py
small templates, small gains,
off by default, experimentalThe 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.
- "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:
- Extensions: libraries written against CPython's C API run through an emulation layer or not at all. NumPy works, but some packages do not.
- Memory and warm-up: it uses more memory and is slow for the first moments of a short program.
- 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.
- Canary: turn it on for a small slice of instances, with the same traffic as the rest.
- 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.
- 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.
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") 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 differWhat 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 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.
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.
- "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 useif key in dord.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
finallyandwith?" -
They use the same exception table, and the design keeps the normal path straight. A
try/finallyor awithblock 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 usewithandfinallyfreely and not avoid them for speed. - "What does a raise cost, in practice?"
-
On the course machine, one raise and catch of a
KeyErrorcost about 130 ns, whiledict.getcost about 23 ns. Here is what that means as arithmetic:raise costruns offline10,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 sSo 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
StopIterationthat ends aforloop 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
tryaffect other optimisations?" -
Not in a way that matters to you. The specialising interpreter treats the code inside a
tryblock like any other code, so loads, arithmetic and calls are specialised in the normal way. There is no penalty for being in atry.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
tryas narrow as possible: only the one call that can raise the exception you handle. A widetrycan 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 bareexceptorexcept Exceptionunless 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.
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")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 differWhat 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.
for _ in range(N):
total += obj.a.b.c.valueHoisted
Look up once.
c = obj.a.b.c
for _ in range(N):
total += c.valueThe 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.
- "How do I get a trustworthy timing?"
-
Use
timeit.repeatand 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.- Warm up: run the code once first, so that the specialiser has settled and caches are warm.
- Same conditions: use the Python version you deploy, an idle machine, and data of production size.
- Repeat: five to ten runs, and report the minimum with the spread.
- 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.cmeant 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
dictaccess 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 thanrow.price. But the readability loss is serious: nobody remembers what index 3 means in six months. ANamedTupleor a dataclass withslots=Truekeeps 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.cwith 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.
- Vectorise with NumPy: replace the Python loop with array operations (Q108). For arithmetic, speed-ups of tens of times are common.
- 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.
- 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.
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("&"))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: 4What 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.
q = f"... WHERE n = '{name}'"
db.execute(q)
# injection possiblet-string
Keeps parts separate.
q = t"... WHERE n = {name}"
db.execute(q) # driver binds ?
# value never joins the textThe 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.
- "Do t-strings stop SQL injection by themselves?"
-
No. A
t"..."literal gives you aTemplateobject, 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
Templatewhere astris expected, such as tocursor.executein 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
Templatesees 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 theto_sqlhelper 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 anInterpolationobject that carries four pieces of information. The template does not apply any of them. The code that consumes the template chooses what to do.- value: the evaluated result, for example the number 19.5.
- expression: the source text inside the braces, such as
"price". - conversion:
!r,!sor!a, or none. - 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 withformat(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
expressionfield is a pleasant extra for structured logging. Fromt"user {user_id}", a logger can record the keyuser_idwith its value 42, with no separate keyword arguments. - "How do they compare with
string.Templateand%?" -
They solve a different problem.
string.Templateis the older tool: it has$nameplaceholders, looks the names up in a dictionary at the moment you callsubstitute, 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:
- f-string: format now, in code you write.
- t-string: keep the pieces, in code you write, and let a function decide how to join them safely.
- string.Template: fill a template text that was given to you at run time.
Never
evalor 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
TemplateandInterpolationtypes instring.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
Templatedirectly. 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.
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))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 forkserverWhat 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.
- "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.
- 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.
- 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.
- Typing syntax and deferred annotations (3.12 to 3.14):
def first[T](...),typealiases 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:
- Removed modules:
distutilsandasyncorewent in 3.12, and old build scripts or libraries that import them stop working. - Deprecations that turn into errors:
datetime.utcnow()warns, and several oldunittestaliases are gone. - Dataclass checks: from 3.11, mutable defaults such as a list are refused more strictly (anything unhashable).
- Changed defaults: in 3.14 the
multiprocessingstart method on Linux moves fromforktoforkserver, 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. - Removed modules:
- "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. Withforkserverandspawn, the child is a fresh interpreter that imports your main module and receives only what you pass it.Code that worked under
forkby accident then fails in a few characteristic ways:- Pickling errors: the target function and its arguments must be picklable, so lambdas and local functions fail.
- Main module runs again: an unguarded script re-executes its top level in each worker (Q73).
- 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'sinitializer=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.
- 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.
- 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.
- 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).
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.
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.util1) 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 runsWhat 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.
ClassLoader finds Foo.class
loads and links it once
static {} runs on first usePython
Modules execute on import.
finder -> spec -> loader
body runs once, cached in
sys.modules, then name boundThe 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.
- "Why is the module cached before its body finishes?"
-
To stop two modules that import each other from looping forever. Suppose
aimportsb, andbimportsa. When Python startsa, it first registers a new, empty module object insys.modules, then runs the body. In the middle of that body,import bstartsb, whose body saysimport a. Python looks insys.modules, finds the half-builta, 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
bthen writesfrom a import A, andAis defined further down ina, 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 xandfrom x import y?" -
Both statements import the whole module
xfirst and cache it insys.modules. They differ in what name they bind in your file, and when the lookup of an attribute happens.- import x: binds the name
xto the module object. Every usex.ylooksyup at the moment of the call. - from x import y: looks up
x.yonce, right now, and bindsyto whatever object it found.
The second form freezes the answer. If someone later rebinds
x.yto a different object, yourystill points to the old one.A common place this bites is testing.
patch("module.func")replaces the name in modulemodule, but a file that didfrom module import funcalready 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 xwithx.y(...)when a name may be patched or reassigned, andfrom x import yfor stable names I use often. - import x: binds the name
- "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.utilfirst importspkg, which runspkg/__init__.py, and only then importsutil. So every import of any submodule pays for everything that__init__.pyimports. A package whose__init__eagerly imports ten submodules and a heavy library makesimport pkg.tinyslow, and this is a common reason for slow CLI start-up (Q74).The habit that follows is to keep
__init__.pynearly 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 ofpython -X importtimeto 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.modulesonly removes the cache. Everything that already imported the module keeps a reference to the old module object. The nextimportcreates a second one by running the body again.The result: two sets of global variables, two copies of each class, and
isinstancechecks 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.reloadis 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.
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")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: aWhat 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.
# a.py
from b import B
class A: ...
# b.py
from a import A # failsBreak it
Third module.
# shared.py: A and B
# a.py
from shared import A
# b.py
from shared import BThe 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.
- "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, thenbruns whileais incomplete, sobsees a partiala. If you start fromb, thenaruns whilebis incomplete, and it isathat sees a partialb.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:
- Your test: imports
bfirst, which happens to be the safe order. - Production: the application's entry point imports
afirst, and the cycle hits the missing name.
Entry points, worker processes,
-mversus 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. - Your test: imports
- "What is
TYPE_CHECKINGfor?" -
It is a constant from
typingthat isFalseat run time andTruefor static type checkers such as mypy and pyright. Code underif TYPE_CHECKING:is therefore seen by the checker and skipped when the program runs.orders.pyfrom __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.nameThe 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_CHECKINGimport for a name you call, subclass, or use inisinstance. That would raiseNameError. - "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.- Acceptable: one or two local imports, each with a one-line comment such as "avoids cycle with orders" or "heavy, rarely used".
- 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:
- pydeps: draws the module dependency graph, and highlights cycles, which helps to see the shape of a mess.
- 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.
- pylint: has a
cyclic-importcheck 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.
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)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.
public static void main(String[] a) {
start();
}
// importing the class runs nothingPython
Guard marks the entry.
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.
- "What does
__mp_main__mean?" -
It is the name a worker process gives to the copy of your main module that it imports. With
spawnorforkserver, 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,defandclassstatements. So the child can find a function such assquareby name, which is how the function you submitted is unpickled and called.Two rules follow:
- Define workers at module level: a function defined inside the
if __name__ == "__main__":block does not exist in the child. - No lambdas or local functions: pickle stores functions by name, and these have no importable name.
- Define workers at module level: a function defined inside the
- "How do I make
python -m packagerunnable?" -
Add a
__main__.pyfile inside the package. When you runpython -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__.pyfrom .cli import main if __name__ == "__main__": raise SystemExit(main())The function
main(argv=None)lives incli.py. It parses arguments, does the work and returns an exit code. Becauseargvcan be passed in, a test can callmain(["--help"])directly, with no subprocess.The same
mainis also the target of a console script. Inpyproject.toml, an entry such asmytool = "mytool.cli:main"under[project.scripts]makes the installer create amytoolcommand. 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.- 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.
- Defaults change: macOS and Windows already use
spawn, and Linux moved fromforktoforkserverin 3.14. Code that was sloppy for years then breaks on an upgrade. - 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
forktoforkserver?" -
Several things that
forkgave for free are gone. A forked child is a copy of the parent's memory, so it has everything. Aforkserverorspawnchild starts empty and receives only what you send it.- 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.
- Picklable arguments: the function and its arguments are pickled and sent, so lambdas, local functions and open handles fail.
- No shared handles: sockets, open files and database connections are not inherited and must be opened in the worker.
- 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.
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")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 differWhat 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.
import pandas
def version():
print("1.0") # still slowLazy
Pay when first used.
lazy import pandas # 3.15
# or: import inside report()
def version():
print("1.0") # fastThe 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.
- "How do I read
-X importtimeoutput?" -
Each line is printed to stderr in the form
import time: self [us] | cumulative | imported package. All times are microseconds.- Self: the time spent running that module's own body, excluding what it imported.
- Cumulative: the self time plus every module it pulled in.
- 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 xandlazy 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.- Module level only: inside a function, a class body or a
try/exceptblock it is aSyntaxError. - Global control: the switch
-X lazy_imports, or the environment variablePYTHON_LAZY_IMPORTS, changes the default behaviour for the whole run. - 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
--helpnever 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.
- Module level only: inside a function, a class body or a
- "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
cProfilewithpython -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:
- Module-level work: a file read, a network call or a big table built when the module is imported.
- Work before argument parsing: loading configuration, connecting to a service or scanning plugin folders in
main()before the arguments are even checked. - 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.
--helpand--versionshould 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
.pyccache help?" -
A little, and it is not where the big gain is. A
.pycfile 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
.pycfiles are created at install time, so users do not pay the first-run cost. In containers with a read-only filesystem, runpython -m compileallat 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.
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))switch interval: 0.005 s | GIL enabled: True
without a lock, two withdrawals of 80 from 100 leave: -60
with a lock leaves: 20What 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.
JVM threads run in parallel;
shared data needs synchronized
/ locks /atomicsPython
Threads take turns.
one thread runs bytecode at a
time; I/O releases the lock;
your invariants still need LockThe 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.
- "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] = valueandqueue.Queue.putcannot 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 atomicx += 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 actEach 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, aqueue.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 withsys.setswitchinterval.The details:
- 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.
- Blocking calls skip it: I/O,
time.sleepand lock waits release the GIL at once, without waiting for the interval. - 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.interpretersand anInterpreterPoolExecutor(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.
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)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 differWhat 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.
def work():
for i in range(N):
total += i % 7
# threads take turnsGIL released
Real overlap.
def work():
hashlib.sha256(buf) # C code
time.sleep(0.2) # blockingThe 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.
- "Does
requestsor a database driver release the GIL?" -
Yes for the waiting part, no for the Python part. When
requestssends 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
redo?" -
The built-in
reengine 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
regexmodule 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:
- Simplify: anchor the pattern, avoid nested repeats, or use plain
str.findorstr.startswithwhen a pattern is not needed. - Split across processes: each process gets a big chunk of the file, not one line.
- Use a different tool: a native engine that is built for it.
Separately, a pattern like
(a+)+bcan take exponential time on some inputs. That is a bigger risk than the GIL. - Simplify: anchor the pattern, avoid nested repeats, or use plain
- "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,zlibandtime.sleepsay 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_THREADSandPy_END_ALLOW_THREADS, and in Cython you usewith 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.
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}")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 benchmarkWhat 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.
with ThreadPoolExecutor(4) as p:
list(p.map(cpu_task, jobs))
# about the same as one threadProcesses
One interpreter each.
with ProcessPoolExecutor(4) as p:
list(p.map(cpu_task, jobs))
# about 4x faster on 4 coresThe 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.
- "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.
- 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.
- 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 offlinework 100 ms: overhead 1 / 101 = about 1 percent work 1 ms: overhead 1 / 2 = 50 percentThe fix for small items is batching: send 500 items at a time (
chunksizeinmap, 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, whileos.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.
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()) 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 differWhat 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.
def hit():
global counter
counter += 1
# load, add, store: 3 stepsSafe
Lock or no sharing.
def hit():
global counter
with lock:
counter += 1The 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.
- "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.
- Lock:
with lock: counter += 1. Simple and correct, and the right default. - 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.
- 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. - queue.Queue: pass events to one thread that owns the total.
- multiprocessing.Value: for processes, with its built-in lock held around the whole update.
- 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.
- Lock:
- "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 += 1is 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:
- Keep the section tiny: only the read-modify-write, never I/O or a long computation.
- Do not share if you can avoid it: one counter per thread, merged at the end, removes the lock completely.
- 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] = vorset.adduses 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.
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}%")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 differWhat 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.
python3.14
sys._is_gil_enabled() -> True
fast single threadFree-threaded
Threads in parallel.
python3.14t
sys._is_gil_enabled() -> False
slower single thread,
parallel CPU-bound threadsThe 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.
- "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 offlinepython3.14 -> (3, 14) GIL enabled: True python3.14t -> (3, 14) GIL enabled: False PYTHON_GIL=1 python3.14t -> (3, 14) GIL enabled: TrueThe third line shows the switch:
PYTHON_GIL=1forces the lock on, andPYTHON_GIL=0forces 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 forcp314twheels 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:
- CPU work in threads:
asyncio.to_threadsends work to a pool. On a GIL build, CPU-bound work there does not run in parallel; on 3.14t it does. - Several loops: you can run one event loop per thread, each on its own core, which is not useful with a GIL.
- 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.
- CPU work in threads:
- "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.
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")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 differWhat 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."
swap python3.14 -> python3.14t
deploy everywhere
check Twitter for bugsPlan
Gates with numbers.
1 target 2 dependency scan
3 thread-safety review
4 benchmark 5 canary 6 decideThe 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.
- "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:
- Dependency: a critical library has no free-threaded wheel, or turns the GIL back on. Then there is nothing to test.
- 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.
- Tail latency: p99 at the target load is worse than today's.
- Races: a data-race failure in stress tests that I cannot fix cleanly.
- 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.
- 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.
- 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.
- 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".
- Use tooling:
faulthandlerto 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.
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.
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.
main: tasks created, now awaiting
callback A (call_soon)
T1 step 0
T2 step 0
T1 step 1
T2 step 1What 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.
# 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 returnsWhy: 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.
- "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 iskqueue, and elsewhere it falls back toselect. 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_waitcall 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)andcall_laterlive?" -
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:- Create: sleep makes a Future and calls
loop.call_later(0.5, future.set_result, None). - Park: the task awaits the future and returns control to the loop.
- Wait: the loop computes its sleep time from the top of the heap and calls
epoll_waitfor at most that long. - 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. - Create: sleep makes a Future and calls
- "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.
uvloopis 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.
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.
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 differWhat 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.
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
heartbeatBlocking call in the handler
The loop is frozen for 50 ms per request.
async def handler():
data = requests.get(URL) # blocks
return data.json()Await an async client
The loop serves others while waiting.
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.
- "How would you catch this before production?"
-
I use three guards, each cheap, each catching the problem at a different stage.
- Debug mode in tests: run with
PYTHONASYNCIODEBUG=1orasyncio.run(main(), debug=True). The loop then logs any callback that holds it longer thanslow_callback_duration(0.1 s by default), and names the culprit. - 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.
- A linter: Ruff has
ASYNCrules that flagtime.sleep,requests.getand blocking file calls insideasync 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.
- Debug mode in tests: run with
- "How big is the thread pool behind
to_thread?" -
The default executor is a
ThreadPoolExecutorwhose size ismin(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 offlinewaves = ceil(100 / 16) = 7 last request waits about 7 x 200 ms = 1.4 sFor 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.
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.
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 tracebackWhat 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.
- "When do I use
await coro()versuscreate_task(coro())?" -
The rule is about whether the next line needs the answer. Use
awaitwhen it does. Usecreate_taskwhen 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 offlineawait 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 aTaskGroupso I cannot forget to collect them. - "What is
ensure_futureand 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_taskwas 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_taskfor coroutines.In new code I use two tools only:
- TaskGroup: when a block of code owns the children. It handles waiting, failure and cancellation for me.
- create_task: for a single background task, where I keep a reference and add a done-callback (Q86).
I read
ensure_futurein 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.rundo 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 useawaitbecause 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 treturns 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 offline42 coroutine twice: cannot reuse already awaited coroutine task twice: 42 42This 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.
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.
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.
try:
await asyncio.gather(a(), b())
except ValueError:
... # b() may still runTaskGroup: owner of its children
Siblings are cancelled and all errors reported.
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.
- "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:
- Run:
results = await asyncio.gather(*calls, return_exceptions=True). - Check each item:
isinstance(r, BaseException)is true for failures and for a cancelled child. Log them with the input that failed. - 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.
- Run:
- "What if two tasks fail at once in a TaskGroup?"
-
You get one
ExceptionGroupthat 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 ValueErrordoes 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 offlineplain 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 fromgather, where only the first error arrived. I also remember that one try statement cannot mixexceptandexcept*. - "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 callresult(), so checkt1.done()andt1.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:
- Wrap: each child runs
try: value = await fetch(x)and catches the errors it expects. - Return: a result that carries either a value or an error message.
- 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.
- Wrap: each child runs
- "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 theirfinallyblocks), 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 raisesTimeoutErrorfor 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
CancelledErrorpass (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.
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?
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.
try:
await work()
except asyncio.CancelledError:
log.info("ignoring") # lostClean up, then re-raise
The cancellation completes.
try:
await work()
except asyncio.CancelledError:
await cleanup()
raiseThe 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.
- "What if my clean-up code needs to
awaitsomething?" -
Cancellation arrives once, as an exception thrown at the current
await, so awaiting in afinallyblock 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
CancelledErrorlands in the clean-upawaitand interrupts it. A database rollback or a lock release might be left half done.For clean-up that must complete, I protect it:
- Keep it short: only the essential step, such as releasing a lease or rolling back.
- Shield it:
await asyncio.shield(cleanup())keeps the inner work running if the outer await is cancelled again. - 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.shielddo?" -
Shield protects the inner work from the outer cancellation. When the task that awaits
asyncio.shield(coro)is cancelled, the caller seesCancelledError, 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:
- You own the inner task: keep a reference to it and make sure someone eventually awaits it, or its error vanishes (Q86).
- 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_fororasyncio.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_foron each step you must work out the remaining time by hand, and three steps of 3 s each allow 9 s in total. With onetimeout(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
rescheduletoo.Both raise
TimeoutErrorto 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 insidetime.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_threadcontinues even when the task that started it is cancelled. The awaiting side stops waiting, but the work keeps running.There are three practical designs:
- Cooperative checks: the work loop checks a flag or an
Eventbetween chunks, say every 100 ms of work, and returns early. - A process: run it in a child process that you can terminate, accepting the lost state.
- 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.
- Cooperative checks: the work loop checks a flag or an
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.
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.
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 = 1What 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.
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.
asyncio.create_task(send_email(o))
# result discardedKeep a reference
A set owns the task until it is done.
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.
- "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.
- Keep the task:
tasks.add(t)in a set owned by the app. - Add the callback:
t.add_done_callback(on_done), whereon_doneremoves the task from the set. - Read the result there: inside it, check
t.cancelled(), then callt.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.
- Keep the task:
- "Is a TaskGroup always the answer for background work?"
-
No. A TaskGroup lives only for the duration of its
async withblock. 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:
- 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.
- An in-process queue with workers: a bounded
asyncio.Queueand a few worker tasks. This adds backpressure and a limit on concurrency. - 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). Thereturn_exceptions=Truepart matters, since cancelled tasks raiseCancelledErrorand 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.runcancels 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.
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.
100 calls x 0.1 s, limit 10: 1.01 s, peak in flight = 10What 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.
await asyncio.gather(
*(call(i) for i in range(100)))Bounded by a semaphore
At most 10 are inside the block.
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.
- "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
BoundedSemaphoredifferent?" -
It adds one safety check. A
BoundedSemaphoreraisesValueErrorif you release it more times than you acquired it. A plainSemaphoreaccepts 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 offlineSemaphore extra release: accepted, counter is now 2 BoundedSemaphore extra release: ValueError: BoundedSemaphore released too many timesWith
async with sem:a double release cannot happen, because the context manager pairs the two for you. So the difference matters only when code callsacquire()andrelease()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.sleepor a library such asaiolimiter.Often I need both. The two limits protect against different failures:
- Rate limiter: keeps the number of starts per second under the provider's quota.
- 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 aCancelledError. 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()andrelease()you would have to place the release in afinallyblock 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.
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.
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.
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 tracebackWhat 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.
- "
to_threadorrun_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 ownThreadPoolExecutorwith a set size, or aProcessPoolExecutorfor CPU work. It does not copy the context, and it takes positional arguments only, so keyword arguments needfunctools.partial.My rule:
- Default:
to_threadfor a blocking library call. - Own pool:
run_in_executorwith a dedicated executor when one slow dependency could use all 16 default threads and starve other work. - Processes:
run_in_executorwith a process pool for CPU-bound code on a normal build.
Both return an awaitable, so the calling code looks the same.
- Default:
- "How do FastAPI and similar frameworks treat
defversusasync defhandlers?" -
The framework decides from how the handler is declared. An
async defhandler runs directly on the event loop, so any blocking call inside it freezes every other request on that worker. A plaindefhandler is sent to a thread pool, so blocking inside it is acceptable, and the loop stays free.Both have limits. The thread pool for
defhandlers is finite (FastAPI uses AnyIO's pool, 40 threads by default), so 40 slow handlers already fill it and the next one waits. Anasync defhandler is cheap but must use async libraries throughout.Take a handler that calls
requests.get(blocking, 200 ms):- As
async def: blocks the loop for 200 ms per call; 40 simultaneous requests finish after 8 s. - 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.
- As
- "How do I use
awaitin 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-levelawaitwork. If you typeasyncio.run(main())there, it fails withRuntimeError: 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 withpython -m asyncio, which runs the loop for you and lets you typeawait ...at the prompt. It is useful for trying an async client by hand.In a script file,
awaitoutside a function is a syntax error, so a file always needs anasync def main()and oneasyncio.run(main())at the bottom.When I copy a snippet from a notebook into a script, the
awaitlines 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 withasyncio.run_coroutine_threadsafe(coro, loop). It returns aconcurrent.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.
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.
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.
- "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, aTypeErrorand aKeyError, and a try block with clauses forValueErrorandKeyErroronly. Both clauses run, one with each matching member, and anExceptionGroupholding theTypeErrorgoes 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
exceptlets 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,breakorcontinueinsideexcept*?" -
No. Using
return,breakorcontinueinside anexcept*block is a syntax error. The reason is that severalexcept*clauses can run for a single raise. Areturnin 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
trystatement:- Collect: in each clause, append to a list or set a flag, for example
failed.append(...). - Finish the try: let all clauses run, and the leftover group propagates.
- 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. - Collect: in each clause, append to a list or set a flag, for example
- "How do I inspect or split a group without
except*?" -
Without
except*, the group object has three tools.eg.exceptionsis 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 beNoneif empty).eg.subgroup(ValueError)returns just the matching part.q89_split.py · Python 3.14runs offlineExceptionGroup('batch', [ValueError('a'), ValueError('c')]) ExceptionGroup('batch', [TypeError('b')]) 3 members in the originalBoth 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 wroteexcept TimeoutErrorwill not catch it any more, and that is a breaking change in behaviour even if no signature changed.I have two honest options:
- Document it: say in the docs that the function may raise an
ExceptionGroup, and show anexcept*example. - 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. - Document it: say in the docs that the function may raise an
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.
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.
req-A: contextvar=req-A threading.local=req-B
req-B: contextvar=req-B threading.local=req-BWhat 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.
{"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 = threading.local()
local.rid = rid
await step()
print(local.rid) # maybe another'sContextVar
One slot per task context.
rid_var = ContextVar("rid")
rid_var.set(rid)
await step()
print(rid_var.get()) # own valueThe 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.
- "When exactly is the context copied?"
-
The context is copied at one moment: when a task is created, through
create_taskorTaskGroup.create_task, and whento_threadstarts 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 offlinechild starts with : req-1 after separate task: req-1 after plain await : set-in-helperThe child saw the parent's value at creation time. The child's
setdid not come back. But the helper awaited directly runs in the caller's own context, so itssetis 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
settokens andresetfor?" -
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:
- Set:
token = request_id.set(new_id)at the start of the request. - Run: call the next handler; everything below reads
request_id.get(). - Reset: in a
finallyblock,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.
- Set:
- "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. Anappendin 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 callingset. 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:
- Default: something immutable, such as
None,"-"or a tuple. - Per request: in the middleware,
seta fresh list or object for this request and store its token. - Readers: treat
Noneas "not inside a request".
- Default: something immutable, such as
- "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.
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.
try (var ex = Executors
.newVirtualThreadPerTaskExecutor()) {
for (var id : ids) {
ex.submit(() -> repo.find(id));
}
} // close() waits for allPython · asyncio
Every function on the path must be async def and awaited. A blocking find would stall the loop.
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.
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()/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.5What 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.
- "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
synchronizedmonitor, 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.
- 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. - Prefer ReentrantLock: in hot paths that wait, since it cooperates with unmounting.
- 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. - Check the JDK release: newer releases reduce pinning for
- "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.
- Pick a world: an async framework means async clients end to end, such as
httpx.AsyncClientand an async database driver. A sync service means plain clients and threads. Half-and-half code is where the bugs live. - Bridge at the edges:
asyncio.runonce inmain, andto_threadfor the one blocking library that has no async version. - Do not spread bridges: a helper that calls
asyncio.runcreates 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.
- Pick a world: an async framework means async clients end to end, such as
- "Is there any Python-side way to avoid colouring?"
-
There is one approach, and it has a cost. Libraries such as
geventpatch the standard blocking calls (sockets, sleep) so that they yield to a scheduler. Plain, ordinary-looking code then runs concurrently, with noasyncorawait. 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.
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.
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 differWhat 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.
# 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 + jitterWhy: 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.
- "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 offlinein 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 flightThat 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.- Cap it: a maximum delay, such as 30 s, so a high attempt number does not wait for minutes.
- Limit attempts: three is a common choice. Then record the URL as failed.
- 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.
- Record state: a row per URL with a status: pending, in progress, done, failed, plus the attempt count.
- Mark done after saving: set "done" only after the result is stored, so a crash in between causes a repeat, never a loss.
- 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.
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).
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).
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 differWhat 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.
# 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.
- "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.interpretershas 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.
- 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.
- Thread view: py-spy shows what each thread is doing. If most samples sit in
recv,selector a database call, it is waiting. If they sit in your own functions, it is computing. - 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.
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.
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)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.
ctx = mp.get_context("fork")
p = ctx.Process(target=f)
p.start() # sees parent's globalsforkserver: fresh child
Clean start; state must be passed in.
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.
- "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.- Pickling: the function and arguments must be picklable. Lambdas, nested functions, open sockets and connections are not.
- 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. - 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 offlinefork 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
DeprecationWarningwhen 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.
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_000Make the invisible visible: Run it.
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 differWhat 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.
with ProcessPoolExecutor(4) as ex:
out = list(ex.map(f, data))
# 20,000 round trips: 2.2 sBetter: big units of work
Ship a slice, return one number.
chunks = [data[i:i+500]
for i in range(0, N, 500)]
out = list(ex.map(f_chunk, chunks))
# 40 round tripsThe 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.
- "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 offline400,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 percentThen 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:
- Shared memory:
multiprocessing.shared_memoryputs 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. - A memory-mapped file:
numpy.memmapor a file on disk, which the operating system caches once and shares across processes. - 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.
- Shared memory:
- "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:
- Reuse the pool: create it once and send many tasks, instead of creating it in a loop.
- Keep imports small: workers should import only what the task needs.
- 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.
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.
child still stuck after 2 s -> deadlock; killing itWhat 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.
/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 runningWhat 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.
# 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 foreverFork a threaded process
Locks held by other threads stay locked.
threading.Thread(target=bg).start()
os.fork() # child may hang on a lockFork first, or spawn
No other thread exists at fork time.
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.
- "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.- Find the stuck child: a worker with no CPU use and a state of sleeping, in
toporps. - Dump it: a deadlocked child shows its main thread inside
lock.acquire,_acquireLockinlogging, or a similar wait. - 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.
- Find the stuck child: a worker with no CPU use and a state of sleeping, in
- "Does Python protect me from this for
logging?" -
Mostly yes, and the reason shows how the problem is handled in general. The standard
loggingmodule registers a function withos.register_at_forkthat, 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.
- Do not start threads at import: create them in a function that runs after the fork.
- Use the post-fork hook: in gunicorn,
post_fork(server, worker), where each worker opens its own database connection and starts its own exporter. - 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_forkexists for it. It takes three callbacks:beforeruns in the parent just before the fork,after_in_parentruns in the parent afterwards, andafter_in_childruns in the child. The trick is to take a library's lock inbefore, 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.
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.
inside sub-interpreter, x = 42
main interpreter cannot see x: nothing is shared
[332833500, 2664667000, 8995500500, 21325334000]
received: hello from the other interpreterWhat 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.
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)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 differWhat 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.
- "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.
Question Free-threaded 3.14t concurrent.interpreters Objects shared? Yes, all No Data races possible? Yes, in your code No, between interpreters Build Separate build Normal build Extension support Needs free-threading flag Needs 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.
- Cost: creating an interpreter is cheaper than starting a process, and the memory overhead is lower, since the process-level resources are shared.
- 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.
- 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
bytesor amemoryview, 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:
- Scope: a pure-Python or well-tested workload, such as CPU-bound parsing, where I control the dependencies.
- 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.
- Fallback: keep the process pool code path behind a setting, so I can switch back at once.
- 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 withmultiprocessing.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.
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.
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 differWhat 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.
parent sees byte 0 = 99 (changed by the child, no copy)
queue (pickled): {'sku': 'A1', 'qty': 2}
Value with lock, 4 procs x 1000 = 4000Why: 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.
- "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 offline1,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.- 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.
- Disjoint writes: give each worker its own slice, such as rows 0 to 999 for worker 1, so no lock is needed.
- Clean up once: the creator calls
close()in every process andunlink()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 intry/finally.I also remember that a shared array has no safe way to grow, so I size it up front.
- "Why does a
Valueneedget_lock()?" -
Because
v.value += 1is not one operation. It reads the number, adds one, and writes it back, which is the same race ascounter += 1in 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.Valueincludes a lock, which you get throughv.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 offlinewith v.get_lock(): v.value += 1The 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:
- Load in the worker: an initializer function reads the data once when the worker starts, into a global, and tasks use it.
- Shared buffer:
shared_memoryor a memory-mapped file for large arrays, so workers read the same bytes (Q95). - 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.
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.
[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.
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.
q = queue.Queue(maxsize=5)
q.put(x) # blocks if full
item = q.get() # blocks if emptyThe 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.
- "
Queue,deque,multiprocessing.Queue,asyncio.Queue— which is which?" -
Four queues, four jobs, and mixing them is a common source of bugs.
- queue.Queue: for threads. It has blocking
putandget, a size limit, andtask_doneandjoin. - collections.deque: a fast double-ended list whose
appendandpopleftare atomic in CPython, but they never block. A consumer must poll, which wastes CPU or adds delay. - multiprocessing.Queue: crosses process boundaries. Items are pickled and sent through a pipe, so they must be picklable and are copied.
- asyncio.Queue: for coroutines on one event loop, with
await putandawait get. It is not thread-safe.
The last point is the trap. If a worker thread calls
put_nowaiton anasyncio.Queue, the loop may never wake up, or the queue's internal state may be damaged. The correct call from a thread isloop.call_soon_threadsafe(queue.put_nowait, item).My rule is to pick the queue by what is on each side: threads, processes or coroutines.
- queue.Queue: for threads. It has blocking
- "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 callget()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:
- 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.
- Put them last: only after the final real item is in the queue.
- Use an unmistakable value:
Noneor a dedicatedobject(), never a value that real work could contain.
If the work is open-ended, I use an
Eventas a stop flag instead. - "When do I need
task_doneandjoin?" -
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
putadds one to the count of unfinished tasks, and eachtask_done()subtracts one.q.join()blocks until the count reaches zero.The rules:
- One task_done per get: call it after the work is finished, ideally in a
finallyso a failure does not skip it. - Call join in the producer: it returns when everything put has been processed.
- Never over-call: an extra
task_doneraisesValueError.
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, andjoinhangs forever. A hang at the end of a batch job is often exactly this. - One task_done per get: call it after the work is finished, ideally in a
- "Does
Lockstill 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] = vandset.adddo 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
Lockdoes 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.
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.
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 differWhat 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.
- "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.
- 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.
- Run a load test at several sizes: for example 5, 10, 20, 40, 80, with realistic queries. Record throughput and p99 latency at each.
- 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.
- Use the driver's pool size: for example, a maximum of 20 connections. Further requests wait for a connection.
- Or add a semaphore:
asyncio.Semaphore(20)around the query, as in Q87, which also covers calls that do not use the pool. - 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_connectionsis often set to 100 by default.There are two fixes, and they can be combined:
- 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.
- 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
SETmay 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.
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.
with ThreadPoolExecutor(8) as pool:
f = pool.submit(calc, 5)
v = f.result() # may raise
# shutdown(wait=True) ran hereThe shift: Same pool-and-future model; Python re-raises the original error, and the with-block replaces the shutdown call.
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.
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.
- "Where is
invokeAllandinvokeAny?" -
Both exist, under other names, as small recipes.
invokeAllmeans run every task and wait:list(pool.map(fn, items))returns results in input order, andwait(futures)returns the finished and unfinished sets.invokeAnymeans take the first success and cancel the rest. In Python I writenext(as_completed(futs)), which hands me whichever future finishes first. One catch:as_completedalso yields futures that failed, so for a true first-success I loop and skip any whoseexception()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 offlinefirst 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()returnsFalseand 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 assleepnotice. Python'scancelbehaves like Java'scancel(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.Eventnamedstop, and the job checksstop.is_set()between steps or waits withstop.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_callbackdo?" -
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.
- 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. - Errors: inside the callback you must call
fut.result()orfut.exception()yourself. An exception raised by the callback itself is logged and swallowed, and nobody is told. - 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. - 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
- "How do futures meet asyncio?"
-
Through two bridges.
loop.run_in_executor(pool, fn, *args)submits to aconcurrent.futurespool and returns an asyncio future you canawait.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_threadsafeto 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 mostmin(32, cpu + 4)threads, which is 16 on this 12-core machine.For CPU work I pass a
ProcessPoolExecutortorun_in_executor, since the default thread pool would not run Python code in parallel. And I never callcf.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.
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...")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.
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")main: KeyboardInterrupt, asking workers to stop
worker: saw stop, finishing current job and exiting
clean exitWhat 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.
t = Thread(target=loop, daemon=True)
t.start()
# process exits; loop is killedEvent: asked to stop
The worker finishes its job and returns.
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.
- "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 offlinedeadline = 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
finallyblocks and noatexithandlers. In-flight work is lost mid-step. Ctrl+C is different, because Python converts SIGINT intoKeyboardInterrupt, but SIGTERM gets no such treatment.sigterm sets the same stop eventruns offlinedef 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
mainis done. A plainshutdown()also waits for every queued job, which can mean minutes.- Make jobs stoppable: pass each job the shared
stopevent and have it check between units of work, or usequeue.get(timeout=...)inside the job. - Drop what has not started: call
pool.shutdown(wait=True, cancel_futures=True). Queued futures are cancelled; jobs already running are left to finish. - Bound the wait: because running jobs cannot be forced to stop, I set
stopfirst, then shut down, so they end within one loop turn.
The
withblock alone is not enough: it callsshutdown(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. - Make jobs stoppable: pass each job the shared
- "What is the asyncio equivalent?"
-
The ideas are the same, but the mechanics differ. Since Python 3.11,
asyncio.runinstalls its own SIGINT handler. On Ctrl+C it cancels the main task, which raisesCancelledErrorinside it and inside every task it awaits, sofinallyblocks andasync withexits run. AfterwardsKeyboardInterruptis raised fromasyncio.run.A task that catches
CancelledErrorand 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 coroutineawait 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.
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.
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 differWhat 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.
# 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 machineWhy: 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.
- "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 offline7 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, nothingAll 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.
- Age of the oldest message: this tells users how late their thumbnails are. A growing age means workers are behind.
- Images per second out: compare with the average of 11.6 per second and the peak target of 116.
- Failure rate and dead-letter count: a spike usually means a bad deploy or a new image format.
- 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.
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.
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.
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.
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.
- "Why not just use cProfile everywhere?"
-
Because it pays a fee on every function call, and that fee distorts the picture.
cProfilehooks 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,
cProfileon 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.
- Attach: on 3.15 run
python -m profiling.sampling attach <pid>. On older versions usepy-spy record --pid <pid>(orpy-spy dump --pid <pid>for a single snapshot of every thread's stack). - Sample a while: about a minute of real traffic. The service is not restarted and is barely slowed.
- 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
ptracerights, and on Linux theptrace_scopesetting or a container's default security profile often blocks it. In Kubernetes I add theSYS_PTRACEcapability 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.
- Attach: on 3.15 run
- "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.
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.
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 differWhat 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.
banned = load_banned() # list
ok = [o for o in orders
if o.id not in banned]Fast: set membership
One hash lookup per order.
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.
- "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 afrozenset, which is an immutable set that is hashable.hashable stand-insruns offlineseen = {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 dictA second route is to keep a sorted list and use
bisectto 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 dandd[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 checkinginand 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 everyfind the record with this idinside a loop becomesby_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.
- Membership against a list inside a loop:
if x in some_listin aforbody or a comprehension. - Per-item list operations:
list.index,list.remove,list.insert(0, x)andlist.pop(0)inside a loop. Each is O(n). - Nested loops over two collections: matching orders to customers by comparing every pair.
- Repeated linear work:
count(),sum()orlen(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.
- Membership against a list inside a loop:
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.
| Operation | list | dict / set | deque |
|---|---|---|---|
| append at end | O(1) amortised | add / set: O(1) avg | O(1) |
| pop from end | O(1) | pop: O(1) | O(1) |
| insert or pop at front | O(n) | n/a | O(1) |
| index by position | O(1) | n/a | O(n) in the middle |
lookup by key / in | O(n) | O(1) avg | O(n) |
| delete by value or key | O(n) | O(1) avg | O(n) |
| iterate | O(n) | O(n) | O(n) |
| sort | O(n log n) | n/a | n/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.
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.
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 differWhat 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.
q = list(range(n))
while q:
q.pop(0) # O(n) eachdeque as a queue
popleft is constant time.
q = deque(range(n))
while q:
q.popleft() # O(1) eachThe 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.
- "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 offlinelen 1 -> 88 bytes len 5 -> 120 bytes len 9 -> 184 bytes len 17 -> 248 bytes len 25 -> 312 bytes len 33 -> 376 bytesOver 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
heapqandbisect?" -
Both turn a plain list into a smarter structure without a new type.
heapqtreats a list as a binary heap:heappushandheappopare 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.bisectdoes binary search in a list that is already sorted, in O(log n).bisect_leftfinds a position, andinsortinserts at the right place.The catch is that the insert is still O(n), because the items after the position must shift along. So
insortin 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 assortedcontainers.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 plainifslow 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.
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_000Make the invisible visible: Run it.
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 differWhat 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.
s = ""
for p in parts:
s += pjoin
Linear by construction.
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.
- "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 asjoinfor 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 offlinepieces = [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.joindemands that every item is already astr. AnintorNonein the sequence raisesTypeError: 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:
joinneeds 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 insidejoin, 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 += chunkonbytesbuilds 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.
- bytearray:
buf = bytearray()thenbuf.extend(chunk)(or+=), which is mutable and grows with the same spare-room trick as a list. Convert withbytes(buf)at the end. - io.BytesIO:
b.write(chunk), thenb.getvalue(). It is also file-like, so library code that expects a file accepts it.
I choose
bytearrayfor simple accumulation andBytesIOwhen something downstream needs a file object. A typical use is reading a download in 64 KB pieces: withbytes +=a 100 MB body is copied thousands of times; withbytearrayit is not. - bytearray:
- "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,
appendin a loop then onesort()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 tinywritecalls 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. 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. 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. Use built-ins:
sum,map,any, comprehensions and the standard library run their loop in C. - 4. Vectorise: numpy or pandas, so the loop is done in compiled code on whole arrays.
- 5. Parallelise: split the rows into big chunks over processes (Q95).
- 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.
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.
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 differWhat 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.
- "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.vectorizedoes not help; it is a Python loop in disguise.For these, I reach for numba (
@njiton 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.
| Option | Pick it when | Cost or catch |
|---|---|---|
| numpy / pandas | the work is whole-array math | needs array-shaped data; no help for branchy per-item logic |
| numba | numeric loops over arrays, quick win with @njit | limited Python subset, compile time on first call, awkward to deploy |
| Cython | speeding up an existing Python codebase gradually, with C types | a 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 users | needs Rust skills and a toolchain; crossing the boundary costs, so keep calls coarse |
| C or C++ (pybind11, cffi) | wrapping an existing native library | manual 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.
# 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.
- "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
bytesand 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(renameddetachin 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 haswith 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.
- 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. - Per Python version, or abi3: by default one wheel per Python minor version. With PyO3's
abi3option, one wheel can serve all versions from a chosen minimum, at some cost in speed and features. - 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.
- 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
- "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.
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.
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 differWhat 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.
class Plain:
def __init__(self):
self.x = 1
self.y = 2
# can add self.z laterSlotted class
Fixed layout, no dict.
class Slotted:
__slots__ = ("x", "y")
def __init__(self):
self.x = 1
self.y = 2
# self.z -> AttributeErrorThe 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.
- "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: floatThere 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-argumentsuper()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 passweakref_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 plainobjectsubclass 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.
- 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. - Change the shape of the data: a tuple or
NamedTuplefor a row,array.arrayor numpy for columns of numbers, interned strings for repeated text (Q20). - 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.
- Measure: use
- "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 raisesAttributeError.
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.
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.
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 differWhat 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.
payload = order.model_dump()
body = json.dumps(payload)One pass, native encoder
The model writes JSON in Rust.
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.
- "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 adatetime.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,UUIDand 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.dumpsreturnsbytes, notstr, 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.
- Paginate: return 100 to 1,000 items per call with a cursor, so no client ever asks for everything.
- 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.
- 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.
- 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. - 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.
- 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.
- The step itself: take a recorded real response (not a toy example) and time old against new encoder with
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.
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.
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.
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 differWhat 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.
- "How do I read
cache_info()?" -
Call
cache_info()on the cached function. It returnshits,misses,maxsizeandcurrsize. The hit rate ishits / (hits + misses). Here is a tiny run withmaxsize=2and six calls with arguments 1, 2, 1, 3, 1, 2:q112_cache_info.py outputruns offlineCacheInfo(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 raisemaxsizein 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_cachehas 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.
- Clear on change: call
func.cache_clear()when the underlying data is updated. Simple, but it drops every entry, not just the stale one. - 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)) - A real TTL cache:
cachetools.TTLCacheexpires 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.
- Clear on change: call
- "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_cachein 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.
| Question | Result |
|---|---|
| 10 million loop iterations, plain Python | 0.65 s (about 65 ns each) |
| same work with numpy | 0.15 s (4.3x faster) |
| 4 CPU jobs: serial / 4 processes | 0.82 s / 0.24 s |
| membership in 100,000 items: list / set | 523 us / 0.038 us |
| JSON of one order: stdlib / orjson | 30.1 us / 3.8 us |
| 40 async requests that wait: blocking / awaiting | about 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.
# 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.
- "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
sleepreleases the GIL, so hundreds of I/O-bound threads work fine.When CPU work needs several cores, there are four ways around it.
- Processes: each has its own GIL, so work runs in parallel. Data moved between them is copied.
- Native code: numpy, Pillow and Rust extensions release the GIL while they work.
- Subinterpreters: each has its own GIL (3.14 has
InterpreterPoolExecutor). - 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.
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.
file size: 11.3 MB
load_all peak 166.0 MB
stream peak 0.1 MBWhat 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.
with open(path, newline="") as f:
rows = list(csv.DictReader(f))
total = sum(float(r["price"])
for r in rows)Stream
Memory stays flat.
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.
- "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 offlinebytes in file : 25 4 str values : 185 dict itself : 184 total (keys shared) : 369So 369 / 25 is about 15 times. The reasons: each
strhas 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.
- DuckDB:
SELECT customer, SUM(total) FROM 'orders.csv' GROUP BY customerreads the file directly, stores data in compact columns, and can spill to disk, so it handles files larger than RAM. - Polars lazy mode:
pl.scan_csv(...)builds a query plan and can run it in a streaming way, in chunks. - SQLite or Postgres: load the rows in batches, add an index, and let the database sort and group on disk.
- 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.
- DuckDB:
- "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 offlinefrom 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()batchedyields 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,
executemanyis still one statement per row inside the driver in some libraries. PostgreSQL'sCOPYstreams 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_sizesetting) and again in the application, by counting bytes as they arrive rather than trusting theContent-Lengthheader. 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'sUploadFilekeeps 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.
- Baseline: build a repeatable load test, record throughput, p50 and p99, CPU, and memory. Without it nothing else counts.
- Profile under load: sampling profile and database slow-query log. Find where time goes.
- Remove waste: N+1 queries, missing indexes, repeated work, list-in-list lookups, double serialisation. Often 2x to 3x.
- Cache and batch: cache stable data, batch database and network calls, add connection pooling.
- Use the hardware: run one worker per core, async or threads for waiting, processes for CPU, native libraries for hot loops.
- 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.
# 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.
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.00xWhat 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.
# 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 ~10xWhy: 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.
- "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.
- 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.
- One change at a time: if I make three changes and the numbers move, I cannot tell which helped or which broke things.
- 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.
- 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 offlineone part (80%) made 10x faster -> 3.57x overall same part made infinitely faster -> 5.00x at mostSo 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.
Step What I record Why it matters Baseline Throughput, p50, p99, CPU, memory Everything else is measured against it Each change Same metrics, same load test, before and after Shows which change earned its keep Running total Overall gain against the 10x target Shows the gap that remains Next candidate The next biggest cost from a fresh profile Prevents 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.
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.
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.
ababab
5.0hints_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.
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 possiblefind_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.
def find_rule(code):
return RULES.get(code)
find_rule(c).amount # may be NoneHints: found by the checker
The error is reported before the run.
def find_rule(code: str) -> Rule | None:
return RULES.get(code)
find_rule(c).amount # mypy: errorThe 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.
- "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
deforclassstatement 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 offlinefrom 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 ValidationErrorvalidate_callchecks and converts the arguments.typeguardandbeartypecheck 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-defsturns 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.
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.
interface Notifier {
void send(String msg);
}
class SmsClient
implements Notifier { ... }
// vendor class without it: noPython · Protocol (structural)
Matching method signature is enough.
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.
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 subclassMake the invisible visible: Run mypy.
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.
- "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
TypeErrorat once, even without a type checker:abstract method enforced at creationruns offlineclass 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 useregister()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_checkabledo?" -
It lets
isinstanceandissubclasswork with a Protocol. Without it,isinstance(x, Sink)raisesTypeError. The check is weak, and this run shows how weak:q117_runtime_checkable.py outputruns offlineTrue FalseThe first line is for a class whose
sendtakes three unrelated arguments, nothing like the Protocol'ssend(msg: str) -> None. It still passed, becauseisinstanceonly checks that an attribute namedsendexists. It does not look at the parameters, the types or the return value. The second line, an object with nosend, correctly fails.So the static checker is the real guarantee, and the runtime check is a quick sanity test. I use
@runtime_checkablesparingly, 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
SinkProtocol can be tested with a few lines, with no mocking library and no inheritance:a three-line fakeruns offlineclass 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 likesink.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 offlineclass Named(Protocol): name: str # must be readable AND writable class Labelled(Protocol): @property def label(self) -> str: ... # readable is enoughThe difference matters. A plain
name: strmeans 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
@propertyin 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.
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.
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.
T = TypeVar("T")
def first(xs: list[T]) -> T:
return xs[0]3.12 bracket syntax
The parameter is scoped to the function.
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.
- "What did the old
TypeVarstyle look like?" -
The old way needed a module-level variable and a separate step:
before and after 3.12runs offlinefrom 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 sameTcan 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_extensionspackage 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
Catas a subclass ofAnimal. Can alist[Cat]be used wherelist[Animal]is expected?For a mutable list, no, and the reason is the write. If the function receives a
list[Animal], it may doxs.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 alist[Animal].For read-only containers it is safe. A
Sequence[Cat]can be used whereSequence[Animal]is expected, because the receiver can only read animals out. That is covariant. The opposite case is contravariant: a function that accepts anyAnimalcan stand in for one that acceptsCat, which is why function parameter types are contravariant.With the 3.12 syntax, the checker infers which one applies from how
Tis used in the class. With the old style, I writecovariant=Truemyself. - "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 writeslist[T].In Java, the compiler checks generics and then erases them. At runtime a
List<String>and aList<Integer>are the same class, which is why you cannot writenew T()orinstanceof 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]) -> Thappily accepts a list of mixed items if the checker is not run. Parameterised types cannot be used inisinstance, sinceisinstance(x, list[int])raisesTypeError.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 usesSequencefor the read-only case.So the mental model carries over, with one change: the checker is the only guard.
- "When is a
typealias worth using?" -
A
typealias 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 offlinetype Json = dict[str, Json] | list[Json] | str | int | float | bool | None type Pair[T] = tuple[T, T] type CustomerId = intSecond, 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
CustomerIdwill accept anyint, including an order id, and the checker will not complain. When mixing them up would be a costly bug, I useNewType("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.
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.
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=2What 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.
| Option | Pick it when | Cost or catch |
|---|---|---|
| TypedDict | typing an existing dict | no runtime check; no methods |
| dataclass | internal domain objects, trusted data | no validation; hints only |
| Pydantic model | input from outside the process | slower 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.
- "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 thanjson.loadsfollowed 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_constructbuilds a model with no checks, which is only safe for data I already trust.If parsing speed is the limit,
msgspecis 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 int2, and"true"can becomeTrue. In strict mode, those are errors.turning strict onruns offlineclass 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
amountis 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.
Type Validates at runtime Mutable Typical use TypedDict No Yes (a dict) Describing a dict you must keep dataclass No Yes, or frozen Internal domain objects attrs class Yes, with validators and converters Yes, or frozen Libraries wanting more than dataclass NamedTuple No No Small, cheap, hashable records Pydantic model Yes, with conversion Yes, or frozen Data 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
NamedTupleis 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.
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 strMake the invisible visible: Run mypy.
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.
def f(x: Any):
x.oops() # accepted
return x + 1 # acceptedobject: prove it first
The checker demands a narrowing check.
def f(x: object):
if isinstance(x, int):
return x + 1The 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.
- "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.
- isinstance:
if isinstance(value, str): value.upper(). Inside the branch,valueis astr. - match:
match value: case int(n): ...orcase [first, *_]: ...narrows by shape and type in one step. - Early exit:
if value is None: raise ..., after which it is not None for the rest of the function. - Type guards: a function returning
TypeIs[Order](3.13+, orTypeGuardin older versions) tells the checker that a True result means the value is anOrder.
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. - isinstance:
- "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 offlinemypy --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-anycatches the most common leak:return json.loads(text)in a function declared to returndict[str, str]. With--strictthis chapter's example gaveReturning Any from function declared to return dict[str, str](Q123).--disallow-any-genericscatches a barelistordicthint, which meanslist[Any].--disallow-any-explicitbans 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 datafrom an untyped helper shows up this way too. - "Is
Anyever 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
Anyfor 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: Anyonly forwards, and when I can do better, ParamSpec (Q121) keeps the signature.The test I apply is: does this
Anyflow 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
objectoverAnywhen I mean "anything", because it forces a check before use. And I leave a comment where anAnyis deliberate, so a later reader does not think it was forgotten. - "What about
castand# 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 offlineuser = cast(User, data) # no check, no conversion; data is unchanged x = parse(raw) # type: ignore[arg-type] # silence one specific errorcastonly changes what the checker believes. Ifdatais not aUser, 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 (isinstanceor 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.
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.
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.
def timed(fn: Callable[..., Any]
) -> Callable[..., Any]:
...
# price("A1", qty="x") passesParamSpec typing
Parameters and result are kept.
def timed(fn: Callable[P, R]
) -> Callable[P, R]:
...
# price("A1", qty="x") failsThe 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.
- "What are
P.argsandP.kwargs?" -
They are the two halves of one captured parameter list. If a function is
def send(to: str, retries: int = 3), the ParamSpecPstands for "(to: str, retries: int = 3)" as a unit.P.argsis the type of the positional arguments in that list, andP.kwargsis the type of the keyword arguments.a typed decoratorruns offlinedef 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 wrapperThey must always be used together, as
*args: P.args, **kwargs: P.kwargs, and only in a function that hasPin 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).- Outer function:
retry(times: int)takes the settings and returns the decorator. Its return type isCallable[[Callable[P, R]], Callable[P, R]], which reads "a function that takes a function and returns one with the same signature". - Decorator:
decorator(fn: Callable[P, R]) -> Callable[P, R], exactly the simple case. - Wrapper:
wrapper(*args: P.args, **kwargs: P.kwargs) -> Rwith@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 samePandR.The easy mistake is to forget the outer layer's return type, so the checker sees the decorator as returning
Any. I usereveal_type(decorated_function)to confirm the signature survived. - Outer function:
- "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]](orCallable[P, Coroutine[Any, Any, R]]if I want to insist on coroutines), and the wrapper is anasync defthat awaits the call.typed async decoratorruns offlinedef 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 wrapperThe common bug is a plain
defwrapper around an async function. It callsfn(...)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,@cachedor@require_rolemay sit on a hundred functions. If it is typed asCallable[..., 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 asAny(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_typeline next to the decorator, which shows the checker's result, so a later change that breaks the typing is noticed. I also keep@wrapsso 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.
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.
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.
- "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_hintsraisesNameError. Second, a name imported only underif 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
FORWARDREFformat for?" -
It is for tools that want as much information as possible without crashing.
annotationlib.get_annotationscan return annotations in three formats, and this run shows them on a class that refers toCustomerbefore that class exists:q122_forwardref.py outputruns offlineVALUE 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'>}VALUEgives real objects and raisesNameErrorif a name is missing.STRINGgives the source text.FORWARDREFgives real objects where they exist and aForwardRefplaceholder where they do not.A serialiser or validator can use
FORWARDREFto 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 withVALUEworks. - "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 callsget_annotations), and then the result is cached.Before, every
defand class statement built its annotation objects during import, such aslist[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
.pycfile.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:
- Any leaked in: a value from
json.loads, an untyped library, or an unannotated function isAny, so everything derived from it is unchecked (Q120). - Untyped function bodies: by default mypy skips the inside of functions without annotations.
castor# type: ignore: a human promise that overrides the checker.- Wrong declaration: a function declared to return
dict[str, str]actually returns whatever the JSON contains. The checker believes the declaration. - Data at the boundary: hints do not validate input, so a
nullin 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.
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 runtimeMake the invisible visible: Run mypy normally, run the program, then run mypy in strict mode.
Success: no issues found in 1 source filedefined
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()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.
- "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 = Truewarn_return_anycatches the leak fromjson.loadsand untyped libraries.check_untyped_defsmakes mypy look inside functions that have no hints, which it skips by default.warn_unused_ignoresreports ignores that no longer hide anything. Anddisallow_untyped_defs, set per package, requires full hints in new or cleaned-up code.Implicit optional (a default of
Nonemaking 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
--strictone package at a time, rather than turning it on everywhere and drowning in errors. - "How do I stop
Nonebugs specifically?" -
The biggest help is to make the possibility of None visible in the type, so the checker forces every caller to handle it.
- Declare it: a function that may find nothing returns
User | None. The checker then reportsuser.nameon that result as an error, until the caller checks. - Narrow it:
if user is None: raise NotFound(uid), and below that line the type is plainUser. - Avoid it where possible: return an empty list instead of None, or raise an error, so callers have nothing to forget.
- Watch the sources:
dict.getreturns an optional value, andre.matchreturns None when nothing matches. Both are common production crashes.
I do not use
assert x is not Noneas the only guard in production code, because Python can strip asserts with the-Oflag 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. - Declare it: a function that may find nothing returns
- "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.
Layer Catches Misses Type checker Wrong types, missing None handling, renamed fields Anything through Any, casts, outside data Tests Wrong behaviour on the cases written Cases nobody thought of Boundary validation Bad or null values from outside Logic errors inside Monitoring What really happens in production Nothing 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
castandignoreuses?" -
I make them countable and visible, so that they cannot pile up unnoticed.
counting the escape hatchesruns offlinegrep -rn "type: ignore" src | wc -l grep -rnE "\bcast\(" src | wc -l grep -rnE "\bAny\b" src | wc -lWith 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
castorignoreneeds 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 = Truemakes 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.
| Checker | Pick it when | Cost or catch |
|---|---|---|
| mypy | the 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 |
| pyright | fast, strict by default; best editor integration through Pylance in VS Code | written 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 projects | beta/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.
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)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.
- "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 withignore_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 isAny, 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
strwhere anintbelongs.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.Listimports, 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.
- 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.
- How fast? Time a full run and a re-run after a one-file change. For big projects, the incremental time decides daily use.
- Does it understand my libraries? Check how it handles the main ones (Django, SQLAlchemy, Pydantic, FastAPI), since plugin support differs.
- 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.
- 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.
- Strict for new code: new modules and files touched in a pull request must be fully annotated (
disallow_untyped_defsper module, via config overrides). - 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.
- Replace
Anyand dict-shaped data: dataclasses or Pydantic models for payloads, so types are true, not wishes. - Automate the boring part: tools such as
MonkeyType(records types at runtime) orpyrefly inferandautotypinggenerate first-draft hints, which humans review. - Ratchet: track the percent of typed functions and the count of
Anyandignoreweekly; 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.
# 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# 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 globallyWhy: 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.
- "How do you get the team to cooperate?"
-
By making it cheap and visible, because a mandate with no help produces
Anyeverywhere. 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
Anywithout 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
Nonethat 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.
- 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. - Split the work: check only changed files with the daemon in pre-commit, and the whole project in CI as the real gate.
- 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.
- Use the cache and the daemon: mypy keeps results in a cache folder, so later runs check only what changed. The daemon, started with
- "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 writeOrder(**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 offlineorder = Order.model_validate_json(body) # raises ValidationError on null qty process(order) # from here on, the types are trueAfter 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
Anycoming from a library with no hints.- Look for stubs: install the
types-*package if one exists, or a newer version of the library that shipspy.typed. - Write small local stubs: for the few functions we use, a
.pyifile with the signatures in astubs/folder, and point the checker at it (mypy_path = stubs). Ten lines are often enough. - 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_importsfor that single module and keep a comment. A full wrapper is for libraries that spread through the code. - Look for stubs: install the
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.
$ 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 = /usrWhat 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.
# one shared cache for all projects
~/.m2/repository/...
# classpath built per build
mvn dependency:build-classpathPython · one environment folder
Packages are installed into a folder that belongs to the project.
.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.
- "What does
include-system-site-packages = truemean?" -
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, thesitemodule puts the venv'ssite-packageson 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 offlinehome = /usr/bin include-system-site-packages = false version = 3.12.3The 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.
- Version clashes: project A needs
requests2.28 and project B needs 2.32. The system folder holds only one version of a package, so one project loses. - 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.
- 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. - Version clashes: project A needs
- "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 runsuv syncto 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 venvcreates the same folder withpyvenv.cfg, abin/pythonlink and asite-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 synccreates the venv if it is missing and makes it match the lock file.My habit: do not activate anything, just run
uv run pytestor.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.
[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.
$ 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-INFOWhat 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.
- "What is the difference between
dependenciesand optional dependencies?" -
dependenciesare required: they are installed every time someone installs the package.[project.optional-dependencies]are named extras the user asks for, such aspip 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 astest,lintanddocs. 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.cliand call the functionmain". When pip or uv installs the package, it writes a tiny launcher file namedpricerinto the environment'sbinfolder. 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.argvitself, or useargparseor Typer. Return an integer and the launcher uses it as the exit code.I test
mainas an ordinary function, and I also tryuv run priceronce in CI to prove the launcher exists. - "Why not keep using
setup.py?" -
Because
setup.pyis a program, and the tools had to run it to learn anything about your package. That has three costs.- 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.
- Slow resolution: a resolver trying many versions had to build or run setup code for each candidate.
- Chicken and egg:
setup.pyneeded setuptools to be installed before the tool could know it needed setuptools.[build-system].requiresfixes that by stating it as data.
pyproject.tomlis declarative, so any tool reads it without running anything. Legacy projects keep working because setuptools still supportssetup.py, and I would not rush to rewrite a stable old package. For anything new, or anything I touch for another reason, I move topyproject.tomlonly. - "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.3and another library needsrequests>=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 aspackaging>=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.
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
...$ uv sync --frozen
Installed 2 packages in 2ms
+ demo-lib==0.1.0 (from file:///.../demo_lib)
+ packaging==26.4What 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.
# requirements.txt
requests>=2
$ pip install -r requirements.txtInstall from the lock
Exact versions and hashes.
# uv.lock committed
$ uv sync --frozenThe 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.
- "What is the difference between
uv lockanduv sync?" -
They do two different jobs.
uv lockdecides which versions to use and writes them touv.lock.uv syncinstalls those versions into the venv so it matches the file.- 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. - 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.
- --frozen: skip resolving altogether and use the file as it is, even if
pyproject.tomlhas changed. - --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.--frozenis for builds where I trust the file fully. - uv lock: reads
- "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 installoruv 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-auditin 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.
| Tool | Pick it when | Cost or catch |
|---|---|---|
| uv | default for new work: fast resolver and installer, venv management, lock file, Python version management, project and script commands, written in Rust | newer than pip; some workflows (very unusual index setups) need checking |
| pip + pip-tools | you want the simplest, most standard pieces: pip-compile writes a pinned requirements.txt with hashes, pip-sync installs it | two tools and files to coordinate; slower; no project metadata management |
| Poetry | an established team workflow with its own poetry.lock, publishing built in | slower resolution, own metadata format historically (now supports PEP 621), plugin ecosystem |
| PDM | standards-first alternative to Poetry, built on the packaging standards (PEP 621) | smaller community |
| conda / mamba | native, non-Python dependencies matter: CUDA, GDAL, compiled scientific stacks, data science teams | separate 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.
$ 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 2msWhat 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.
- "Can I mix conda and pip?"
-
Yes, and it is common in data science teams, but the order and the rules matter.
- 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.
- Pip second: install only what conda does not have, such as a small pure-Python package. Do it at the end, once.
- No replacing: do not let pip upgrade or replace a package conda installed. Conda cannot see that change, and a later
conda installmay undo it or leave a half-broken mix.
Write both lists in one
environment.yml: the conda packages and a nestedpip: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.txtgood 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 withpip install --require-hashes -r requirements.txtchecks 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 withuv export, and with pip-toolspip-compiledoes 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.
- Metadata: a project using PEP 621
[project]works with uv directly. Older Poetry files with[tool.poetry]need their dependencies copied into[project]. Arequirements.txtcan be added withuv add -r requirements.txt. - Lock: run
uv lock. It resolves fresh versions, which may differ from the old lock. - Compare: list old and new versions side by side. Any package that jumped a major version is a surprise to read about first.
- 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.
- Metadata: a project using PEP 621
- "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.14to fetch an interpreter,uv python listto see what is available, anduv python pin 3.14to write a.python-versionfile 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-pythoninpyproject.toml. When you runuv 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.
$ 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-INFOWhat 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?
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-anyWhat 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.
- "What does
manylinuxmean?" -
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_28needs glibc 2.28 or newer, and pip checks that your system has it before choosing the wheel. Older names such asmanylinux2014are aliases for particular versions.On the course machine the interpreter accepts these tags, newest first:
q130_tags.py outputruns offlinecp312-cp312-linux_x86_64 cp312-cp312-manylinux_2_39_x86_64 cp312-cp312-manylinux_2_38_x86_64Alpine Linux uses musl, not glibc, so it needs
musllinuxwheels. 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 extensionsmaturindoes 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.14tand its wheels are taggedcp314t. A normalcp314wheel 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 nocp314twheel 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
cp314twheels. - "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.
- Dry run:
pip install --dry-run -r requirements.txt, oruv pip install --dry-run, resolves everything and prints which package and which file it would pick. - Binary only:
pip download --only-binary :all: -r requirements.txt -d /tmp/wheelsdownloads wheels and fails immediately if some package has only an sdist. That error names the package that would have compiled. - Look at the name: in the output, a file ending
.tar.gzis 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.
- Dry run:
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.
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__)"service A: venv svcA -> packaging 24.0
service B: venv svcB -> packaging 25.0What 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.
// one classpath per application
java -cp app-a.jar:guava-31.jar A
java -cp app-b.jar:guava-33.jar BPython · environments
One folder per application, one interpreter process each.
svcA/.venv -> packaging 24.0
svcB/.venv -> packaging 25.0
# each service: its own lock fileThe 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.
- "What if both libraries must run in the same process?"
-
Then they need versions that work together, because one process has one
sys.modulesand can hold only one copy of a package under one name. There is no clean way around that, only choices.- 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.
- Upgrade the lagging one: if library B needs an old release of A, I update B or open a pull request against it.
- 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 thePATHand 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.
- 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.
- Automatic updates: a bot (Renovate or Dependabot) opens upgrade pull requests in every repository, so no service silently falls two years behind.
- 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-packagesfor 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-packageswould 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.
# 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.pyThe 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.
$ 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.
shop/
shop/__init__.py
tests/
# python -c "import shop" -> works
# even though nothing is installedsrc layout
Imports require an installed package.
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.
- "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
pythonorpytestfrom the root does not findpriceruntil it is installed in the environment. If you forget, you seeModuleNotFoundError. In practice the tools hide this:uv syncinstalls the project in editable mode, anduv run pytestsyncs first. Newcomers still find the extra folder strange, and some editors need to be told thatsrcis 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 throughimportlib.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 setpackage-dataorinclude-package-data. Then you read them withimportlib.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.resourcesalso 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 syncorpip install -e ., the environment gets a.pthfile or an import hook that points at yoursrc/folder.import pricerthen 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.
- Versioning: semantic versioning with the version taken from a git tag (
hatch-vcsor a release bot), so the tag is the single source of truth. A major version means a breaking change. - 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.
- 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. - 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.
- Roll out: consumers pin through their lock files; a bot opens upgrade pull requests in all 30 repositories, so adoption is visible and reviewable.
- 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.
# 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_INDEXMake the invisible visible: What the build step really produces, shown earlier for a tiny library.
$ 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.
- "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.
- Lock files: every service pins its own version, so publishing 3.0.0 changes nothing in production until a service chooses to upgrade.
- 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.
- 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
DeprecationWarningnaming 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 steps1. 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.1Step 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-directflag for direct dependencies only.The lowest job finds a classic bug: I wrote
packaging>=20but 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.
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.
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 connMake the invisible visible: Run with -s to see the prints in order.
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.
- "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
paramsto the fixture decorator, and pytest runs every test that uses the fixture once for each value. The current value is inrequest.param.It looks like this:
@pytest.fixture(params=["sqlite", "postgres"])followed bydef db(request):which builds the right backend fromrequest.param. A test that takesdbas an argument then appears twice in the results, astest_save[sqlite]andtest_save[postgres].This differs from
@pytest.mark.parametrizein 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.
- 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. - Fixture: when it needs teardown after the test, uses other fixtures such as
tmp_pathormonkeypatch, or is shared by many test files throughconftest.py. - 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.pyfiles 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. - Plain function: when it only builds a value, for example
- "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-randomlyor 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.
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) == 20Make the invisible visible: Run them.
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.
# 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.
patch("pricer.rates.fetch")
# service.fetch is still realPatch where it is looked up
The name the code reads is replaced.
patch("pricer.service.fetch")
# service calls the mockThe 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.
- "How does
monkeypatchdiffer fromunittest.mock.patch?" -
Both undo their change afterwards, so the real difference is the extras.
monkeypatch.setattris simple replacement, andpatchbuilds a mock object.monkeypatchis 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.patchreplaces the target with aMagicMockby default, which records calls. You can then assertmock.assert_called_once_with(...), setreturn_valueorside_effect(to raise an error, or return different values per call), and useautospec=Trueto 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 usepatch. 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 fetchon its first line. Every call executes that import, which looks upfetchinpricer.ratesat that moment and copies it into a local name. If your test patchedpricer.rates.fetchbefore the call, the import finds the fake. Patchingpricer.service.fetchwould fail withAttributeError, because that name does not exist in the service module.A module-level
from rates import fetchshows the opposite case, where the copy is made once at import:q135_patch.py outputruns offlinepatched where defined : real patched where used : fakeI 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
MagicMockhas every method you ask for. If you writeclient.fetch_rate("USD")but the real method is namedget_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), orpatch("pricer.service.RatesClient", autospec=True), builds the mock from the real object. It copies the names and the signatures. A misspelt method raisesAttributeError, and a call with the wrong arguments raisesTypeError, 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_setwhere 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 fetchto using a client object. Every test that patchedpricer.service.fetchbreaks, 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].
@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.
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)) > 0Make the invisible visible: Run only the fast ones.
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 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 differWhat 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.
- "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 examplepytest -k threeorpytest "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.
- Named cases:
pytest.param(0, "0.00", id="zero quantity")makes the report saytest_total[zero quantity]. A failure then reads like a sentence. - 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. - 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.
- Named cases:
- "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".
- 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.
- Real network: HTTP calls to a sandbox or DNS lookups that time out.
- Real waiting:
time.sleepor retry back-off that waits for real seconds. - Heavy imports: loading a large library in many modules, or an application that builds all its objects at import.
- Expensive function-scoped fixtures that could be shared safely.
I do not guess. I run
pytest --durations=20and look at the slowest tests and the slowest set-ups, then profile one of them withcProfileif 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.
| Choice | Pick it when | Cost or catch |
|---|---|---|
Mock (Mock, patch) | check an interaction: "was send called once with these arguments?"; simulate an error that is hard to produce | ties 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 client | you 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, migrations | slower (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.
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.
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.
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.
client = FakeRates({"EUR": 2})
assert price(client, "EUR", 10) == 20The 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.
- "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 CONFLICTdetails, case sensitivity and date handling all differ too. A test that passes on SQLite says little about a query that usesjsonborFOR 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.
- 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.
- 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).
- 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.integrationso 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:
- Side effects: the behaviour is "an email was sent once". A mock records the call, and
assert_called_once_withproves it. - Failures: a timeout, a connection reset or a 503 is hard to make a real service produce on demand.
side_effect=TimeoutErrormakes the dependency fail exactly when you want, so you can test the retry or the fallback. - Unavailable dependencies: a payment provider or an external system with no test mode cannot be run in tests.
I use
create_autospecso 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.
- Side effects: the behaviour is "an email was sent once". A mock records the call, and
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.
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)) == centsMake the invisible visible: Run it.
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.38sWhat 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.
def test_split():
assert sum(split(100, 4)) == 100Property test
Checks the rule for many generated cases.
@given(integers(0, 10_000), integers(1, 10))
def test_split(c, p):
assert sum(split(c, p)) == cThe 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.
- "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.
- Round trip: does an inverse exist?
decode(encode(x)) == xis the standard one. - Invariant: what stays the same? The total after splitting is the same as before. The number of items out equals the number in.
- Idempotence and order: does doing it twice equal doing it once, and does input order matter?
sorted(sorted(x)) == sorted(x). - 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. - Round trip: does an inverse exist?
- "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)andst.booleans(). Composite ones build on them:st.lists(st.integers(), min_size=1),st.tuples(...), andst.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
.hypothesisfolder). 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.
_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 _cacheMake the invisible visible: Run both together, then the second one alone.
=========================== short test summary info ============================
FAILED test_order.py::test_b_assumes_empty_cache - AssertionError: assert 'ra...
1 failed, 1 passed in 0.30s. [100%]
1 passed in 0.12sWhat 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.
import pytest
import test_order
@pytest.fixture(autouse=True)
def clean_cache():
test_order._cache.clear() # ✅ start clean
yield
test_order._cache.clear() # ✅ leave clean2 passed in 0.14sWhy: 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.
- "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.
- 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.
- 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. - 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-randomlyprints 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--lfflag 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.
- 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.
- 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.
- Environment: a different time zone (CI often runs in UTC, laptops do not), locale, environment variables, or Python version.
- 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.
- Random order from the start: install
pytest-randomlyin CI. Every run uses a different order and prints its seed, so a hidden dependency fails soon and can be replayed. - Fixtures with teardown: a test that changes the world uses a
yieldfixture,monkeypatchortmp_path, so the clean-up happens even when the test fails. - 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.
- 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.
- Random order from the start: install
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.
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.
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.
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()1 passed in 0.18sWhy: 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.
- "pytest-asyncio or anyio?"
-
I choose by what the project already uses, and I use one plugin per project.
pytest-asynciois 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.asynciorun as async, and async fixtures need@pytest_asyncio.fixture. In auto mode, everyasync deftest 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 plainMockdoes 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(inunittest.mock) returns a coroutine that resolves to thereturn_value, and it records calls and supportsside_effecttoo, so you can make the awaited call raise an error. It also has assert helpers such asassert_awaited_once_with.q140_asyncmock.py outputruns offline42 TypeError: object Mock can't be used in 'await' expressionThe first line is the AsyncMock being awaited. The second is what a plain Mock does. I use
create_autospecorpatch(..., 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.sleepfor 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.
- Inject it: give the function a
sleepparameter that defaults toasyncio.sleep. The test passes an async no-op that records the delays it was asked for. - Patch it:
monkeypatch.setattr("pricer.client.asyncio.sleep", fake_sleep), withfake_sleepanasync defthat does nothing. Patch where it is used (Q135). - 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.
- Inject it: give the function a
- "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.Eventor 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.
- 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.
- 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.
- Money rules:
Decimalor integer cents only; tests that fail if afloatsneaks in; explicit rounding mode tests. - Golden-file tests: real, anonymised statement files and the expected result, to catch parsing regressions (encodings, formats, signs).
- Integration tests: the real database in a container: transactions, unique constraints, concurrent runs, rollback on failure.
- Failure and replay: what happens when the run dies halfway; re-running must not double-post. Test idempotency keys.
- 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.
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 - lcfrom 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.
> 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.01sWhat 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.
- "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_UPfor 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.
- 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.
- 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.
- 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.
- 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.
- Mutation testing: a tool such as
mutmutchanges 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. - 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.
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.
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(): 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: 1What 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.
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))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 sWhat 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.
while True:
item = q.get()
handle(item) # raises -> deadFailure inside the loop
Log it, set it aside, keep going.
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.
- "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.
- Age of the oldest message: if the oldest message has waited 20 minutes and the number keeps rising, nobody is consuming.
- 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.
- 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.excepthookdo?" -
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 withexc_type,exc_value,exc_tracebackandthread. A good hook does three things:- Log: write the traceback through the standard logging system with the thread's name, so it carries the usual fields.
- Count: increment a metric such as
worker_crashes_totalthat an alert watches. - 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 insocket.recv, inlock.acquireor 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.
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.
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.
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.
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.
- "Why store the zone name instead of the offset?"
-
Because an offset such as
+01:00is true for one date only, while a zone name carries the rules that change over the year.Europe/Berlinis +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 letszoneinfocalculate 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
zoneinforeads them from the operating system or from thetzdatapackage. Where the OS has no data (Windows, some slim containers) you must installtzdataand 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
foldattribute.On 1 November 2026, New York clocks go back from 02:00 to 01:00, so 01:30 occurs twice.
fold=0means the first occurrence andfold=1the second. Here is the real output of the two cases:q143_fold.py outputruns offline0 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:00The 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.
- Inject the clock: the scheduler asks a
clockobject 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. - 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_YorkandEurope/Berlin, which change on different dates. - Odd offsets:
Asia/Kolkatais +05:30, so code that assumes whole hours fails there, andAsia/Kathmanduis +05:45. - 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.
- Inject the clock: the scheduler asks a
- "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,
timestamptzstores 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 plaintimestampstores 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) becausetimestamptzdoes 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.
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.
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.97What 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.
total = 0.0
for line in lines:
total += line.price * line.qty
round(total, 2) # 2.675 -> 2.67Decimal: exact decimals
Built from strings, rounded on purpose.
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.
- "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
bigintholds them exactly, and an API that sends1999has no formatting trap. The cost is that you must know each currency's exponent: yen has none, dinar-type currencies have three.Decimalis 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
Decimalfor 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 offline3333 1 [3334, 3333, 3333]- Divide: 100.00 is 10000 cents.
divmod(10000, 3)gives 3333 each and a remainder of 1. - Distribute the remainder: one extra cent goes to the first person, giving 3334, 3333 and 3333, which sum to 10000.
- 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).
- Divide: 100.00 is 10000 cents.
- "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.quantizewith 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 usewith 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
quantizeat defined points with a named mode. - "Is a frozen dataclass
Moneyworth it?" -
Yes. A small
Moneyclass moves the rules from many scattered places to one place, and the type checker helps to enforce them.The class holds
amount: Decimalandcurrency: str, and it is a frozen dataclass (see Q10 and thepat-frozen-valueidiom), 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
amountandcurrencyas 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.
- 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. - Request id from a context variable: set once in middleware (reuse the incoming
X-Request-IDheader 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. - Levels with meaning: ERROR means someone should look; WARNING is unexpected but handled; INFO is business events; DEBUG is off in production. Use
log.exceptionto keep tracebacks. - Do not slow the request: logging to a slow sink inside the request thread adds latency. Use a
QueueHandlerso a separate thread writes. - Control volume: no per-item logging in hot loops; sample noisy events; rate-limit repeated errors.
- Safety: never log secrets, tokens or full card numbers; scrub personal data.
- 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.
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"){"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.
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()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 differWhat 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("saved order", order.id)Structured, with context
JSON line with the request id.
log.info("order saved",
extra={"order_id": order.id})
# request_id added by a filterThe 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.
- "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-IDheader, or thetraceparentheader if the platform uses distributed tracing. If neither exists, I create a UUID. I then store it in aContextVar(Q90), so that it follows the request throughawaitcalls 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.
- "
printorlogging?" -
Use
logging.printis 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,
printhas 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.
structloglets you attach fields to a logger and keep them:log = log.bind(order_id=7)and then every later line fromlogincludesorder_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 tologginghandlers, 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.
- Levels with a budget: INFO only for business events (order placed, payment captured). DEBUG stays off. No log lines in hot loops.
- 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.
- Rate limiting: a failing dependency can repeat the same error 10,000 times a minute. Log it once with a count.
- 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.
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.
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.
try:
conn.execute(INSERT, args)
except Exception:
passIn review: handle what you expect
A named error is handled and visible; the rest surface.
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.
- "Is catching
Exceptionever 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 withlog.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,
Exceptiondoes not includeKeyboardInterruptandSystemExit, which is the reason I never write a bareexcept:. In asyncio,CancelledErroris also not anException, so cancellation still propagates. - "What about
contextlib.suppress?" -
contextlib.suppressis fine for one specific, harmless exception around one statement. That is the opposite of a broadexcept: 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 withexcept Exception: passaround a database call, which hides a duplicate key, a lost connection and a typo in the query alike.Ruff encourages it: rule
SIM105suggests replacing a narrow try, except and pass withsuppress.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.pytry: repo.save(order) except IntegrityError as exc: raise OrderNotSaved(order.id) from excThe
from excsets__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
OrderNotSavedwithout 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.
BLE001flags a blindexcept Exception,S110flags a try, except and pass,E722flags a bareexcept:, andSIM105suggestscontextlib.suppressfor 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: BLE001comment 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.
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.
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.py
import os
TAX = float(os.environ["TAX_RATE"])
# every import needs the variableConfig as a function
Work happens when you ask, with an injectable source.
# 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.
- "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.environor 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_cacheonget_settingsin 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 offline0.2 0.2 0.5The 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.setenvmust also callget_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
mainand pass it in. Then the cache and its clean-up disappear, and each test creates its own object. - "Why not read
os.environdirectly 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.
- 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.environcalls they have to search the code. - 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". - 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. - 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
- "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
SecretStrin Pydantic. Printing or logging that object shows**********, and the real value is only available through an explicitget_secret_value()call. That means an accidentallog.info(settings)or a traceback with the repr of the object does not leak the password.Other rules I enforce:
- no secrets in
.envfiles 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.
- no secrets in
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="".
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.
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")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 CSVsWhat 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.
$ 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-8What 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.
# 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.
- "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 a9for é are shown as two characters. Our script output showed this exact mix-up:q148_encoding.py outputruns offlineb'\xc3\xa9' -> é utf-8-sig starts with: b'\xef\xbb\xbf'The second line is the byte-order mark that
utf-8-sigwrites 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-sigor 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) raisesUnicodeDecodeErrorat 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-normalizercan 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.- Standard streams:
sys.stdout,sys.stdinandsys.stderruse an encoding taken from the locale. Printing an accented name into a pipe under the C locale in an old setup can raiseUnicodeEncodeError. - 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.
- Containers: minimal images often have no locale. I set
LANG=C.UTF-8orPYTHONUTF8=1in 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.encodingandlocale.getpreferredencoding(). - Standard streams:
- "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 passencoding="cp1252"explicitly for those files.To prepare, I search for
open(calls withoutencoding, 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 becomesNone 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.
@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.
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.
| Area | Java habit | In Python |
|---|---|---|
| Wiring | Spring container, annotations | constructor arguments, composition root in main |
| Contracts | interfaces | Protocol (Q117) |
| Values | Lombok, equals/hashCode | @dataclass(frozen=True, slots=True) |
| Errors | checked exceptions | exceptions with domain types; handle at boundaries (Q146) |
| Collections | Streams | comprehensions, generators (Q58) |
| Concurrency | thread pools, virtual threads | asyncio, processes, or free-threaded build (Q91, Q93) |
| Build | Maven / Gradle | uv, pyproject.toml, lock file (Q128) |
| Safety net | compiler | type 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.
- "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
Builderwhere 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.
- Replay: record production requests, with sensitive data removed, and send the same requests to both services. Compare status codes, bodies and headers.
- 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.
- 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
BigDecimalagainst PythonDecimalmodes), 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.
| # | Check | Why it matters | Idiom |
|---|---|---|---|
| 1 | No mutable default arguments or shared module-level state | defaults are created once; requests leak into each other | None default |
| 2 | No broad except that hides failures; resources use with | silent failures and leaked connections are found weeks later | context manager |
| 3 | No blocking calls inside async def | one call stalls every request on the loop | to_thread |
| 4 | Tasks are owned: TaskGroup or saved references; cancellation re-raised | tasks vanish, errors are lost, shutdown hangs | TaskGroup |
| 5 | Types at public boundaries, no new Any, validated input | the checker only protects what it can see | Protocol |
| 6 | Money is Decimal or cents; times are timezone-aware UTC | float and naive time give wrong answers that look right | frozen value |
| 7 | No O(n) lookups in loops; performance claims come with a measurement | list-in-loop and guesses cause the slow endpoint | profile first |
| 8 | Decorators use wraps; closures in loops bind values; caches are bounded | lost names, last-value bugs and memory leaks | wraps |
| 9 | Tests are independent, patch where used, fast, and assert outcomes | order-dependent and mock-heavy suites hide bugs | patch where used |
| 10 | Dependencies locked; config injected, not read at import | a deploy must equal what was tested | lockfile |
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.
# 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.
| Check | Tool |
|---|---|
| 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, 7 | review 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.
- "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, whendefruns, 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
Noneand 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
B006catches 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
Anyorcastortype: ignoreneeds 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.attrreally 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
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
| Idiom | Problem | Solution |
|---|---|---|
| None default | A 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 immutable | A 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 alive | A 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 object | Money 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
| Idiom | Problem | Solution |
|---|---|---|
| Keep __eq__ and __hash__ consistent | Defining __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 manager | A 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 descriptor | The 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 records | Each 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
| Idiom | Problem | Solution |
|---|---|---|
| Always use functools.wraps | A 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 closure | Lambdas 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 pipeline | Reading 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 self | An 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
| Idiom | Problem | Solution |
|---|---|---|
| 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 them | Two 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 loop | A numeric Python loop runs at interpreter speed. | Push the loop into compiled code: numpy, builtins like sum, or native extensions. |
06 · Concurrency
| Idiom | Problem | Solution |
|---|---|---|
| Move blocking calls out with to_thread | A blocking call inside async def freezes every request. | Run it with await asyncio.to_thread(...) or an executor. |
| Run related tasks in a TaskGroup | With 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 Semaphore | Hundreds of simultaneous outbound calls overload the downstream service. | Wrap the call in async with asyncio.Semaphore(n). |
| Process pool with big units of work | Tiny 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 contextvars | Thread-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 task | The 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
| Idiom | Problem | Solution |
|---|---|---|
| Describe behaviour with a Protocol | An 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 ParamSpec | An 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 used | Patching 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 globals | Shared module-level state makes tests order-dependent. | Use function-scoped fixtures with yield teardown. |
| Lock every dependency, and install from the lock | A transitive dependency upgrades itself between test and deploy. | Commit uv.lock and install with uv sync --frozen. |
| Profile first, then change one thing | Optimising by guess fixes the wrong code. | Measure with a profiler, fix the hot spot, and measure again. |