Python Fundamentals — The Prerequisite Primer
"You already know how to program. This is the six-hour bridge so Python stops being the thing you're translating in your head."
01 · The hookWhy a Strong Engineer Bounces Off Module 01
The Python you need before the rest of the course: what a name really points at, the idioms you will read every day, and the two facts about the runtime that explain most performance surprises.
"Nine years of TypeScript. I've shipped event loops, generics, decorators-by-another-name.
I opened Module 01 feeling confident — and the third code block was
async def summarize(client: httpx.AsyncClient, ticket: str) -> str:
sitting directly on top of {t.id: t.text for t in tickets}.
I understand async. I understand type annotations. I understand map-with-a-condition. But five unfamiliar spellings of things I already knew landed in the same ten lines, and my brain rendered the whole page as noise.
I closed the tab and told myself I'd come back later. That was three weeks ago."
Nothing in that code block is hard. async def is async function.
The type hints are TypeScript annotations with the colon moved. The curly-brace thing is a
dict comprehension — a map and a filter wearing one
outfit.
Marcus bounced not because the ideas were new but because five pieces of surface syntax arrived at once, each costing a little translation effort, and the total overran his working memory.
That's a syntax problem, not an ability problem — and syntax problems have a cheap, permanent fix: one focused pass, done before the concepts start stacking. This appendix is that pass. Finish it and Module 01 will feel natural.
Before we start fixing spellings, look at exactly what landed on Marcus, next to the thing he already knew. Every row below is a translation he could have done in a second on its own. Five of them arrived inside the same ten lines, and that pile-up is the whole of the problem.
- The five spellings. Read the rows left to right. Each Python spelling on the left is the same operation as the one on the right, which Marcus writes without thinking. Not one of them is a new idea. The fourth row is the only one that even changes shape, and it is still a map over a list.
- The pile-up. One translation costs a second of attention. Five of them, in the same screenful, cost more attention than anyone has spare while also learning what the code is for. That is why a confident engineer closed the tab, and why the cure is to meet the five spellings once, on their own, before any concept rides on them.
Honest prerequisite check: this appendix assumes you already program fluently in some language — it moves fast and skips "what is a variable". If you're new to programming itself, do the official Python tutorial or Automate the Boring Stuff first (both free), then come back. No shame in it — this page will still be here, and it'll go three times faster.
02 · The rosetta stoneThe Same Ten Operations, Three Languages
Marcus lost three weeks to ten lines. Before we repair any single line, he needs the
map that says how much of Python he already owns, which is about nine tenths of it under different
spellings. This section is that map: ten operations he performs every day, in his language and in
Python, side by side. The habit being replaced here is the silent translation step, reading
def and thinking function. Seeing both spellings together once is cheaper
than meeting them one at a time in the middle of a lesson about something else.
You know roughly 90% of Python already — you just know it under different spellings. The table below is the whole translation layer: ten operations you perform daily, side by side. Skim your column, then read Python's. Everything after this section is the remaining 10% — the parts Python does differently, not just differently-spelled.
| Operation | JS / TS | Java | Python |
|---|---|---|---|
| Variable | const n = 3; | int n = 3; | n = 3 |
| Function | function f(x: number): number { return x * 2; } | int f(int x) { return x * 2; } | def f(x: int) -> int: return x * 2 |
| Class | class User { constructor(name) { this.name = name; } } | class User { User(String name) { this.name = name; } } | class User: then def __init__(self, name): self.name = name |
| Filter + map | xs.filter(x => x > 0).map(x => x * 2) | xs.stream().filter(x -> x > 0).map(x -> x * 2).toList() | [x * 2 for x in xs if x > 0] |
| Dict lookup w/ default | m.get(k) ?? 0 | m.getOrDefault(k, 0) | d.get(k, 0) |
| String interpolation | `p95 is ${ms}ms` | String.format("p95 is %dms", ms) | f"p95 is {ms}ms" |
| Null check | if (x == null) | if (x == null) | if x is None: |
| Error handling | try {…} catch (e) {…} finally {…} | try {…} catch (IOException e) {…} finally {…} | try: / except ValueError as e: / finally: |
| Import | import { thing } from "./mod" | import com.acme.Thing; | from mod import thing |
| Iteration | for (const x of xs) | for (var x : xs) | for x in xs: |
Three global rules the table implies, worth stating once.
- Indentation is the block syntax. A colon opens a block; the indented lines are its body. No braces to forget.
- Everything is an object. Functions, classes, modules — all first-class values you can pass around.
- Names are references, exactly like Java object references or JavaScript. Assignment never copies, which is behind half the gotchas in Watch it break.
The first of those three rules is the one that looks strangest in a screenshot, so here it is drawn once. The same tiny function, in braces and in indentation, with an arrow from each piece of punctuation to the thing that replaced it.
- The braces version. The dashed bar on the left runs from the opening brace to the matching closing brace. That bar is the function body, and the compiler finds it by counting braces. Your indentation is a courtesy to human readers; the machine ignores it.
- The Python version. The dashed bar on the right runs down the indented lines. That bar is the same body, and now the machine reads the indentation itself. A colon ends the line that opens a block, every time:
def,if,for,while,try,with,class. - What it buys and what it costs. Four lines instead of six, and no closing brace to lose in a merge. The cost is that a wrong indent is a real change in meaning, so the editor's four-space rule matters. Python 3 refuses to run a file that mixes tabs and spaces ambiguously, so the classic horror story cannot happen silently.
03 · Core PythonValues & Collections — Four Containers, Four Jobs
The rosetta table handed Marcus back the nine tenths he already knew. The remaining tenth starts here, with the four containers that every line of course code moves data through. The habit being replaced is reaching for one growable array for everything: Python asks you to choose between four, and the choice tells the next reader what you promised. This section also carries the single fact behind four of the five traps in section 10, and it is not about containers at all: a name is a pointer, not a box.
Python ships four workhorse collections, and course code uses all four deliberately.
list is your resizable array (ArrayList, JS array). tuple is a
fixed-shape, immutable record — the "returns two things" type, and the only sequence you can use as a
dict key. dict is your hash map, and it's the load-bearing structure of the entire AI
stack: every JSON payload, every API response, every config is a dict. set is
membership and uniqueness at O(1) — dedupe and "have I seen this?" checks.
list is the default when none of them says otherwise.- dict — you look things up by name. Ask this question first, because it is the one that changes your code the most. Every JSON body, every API reply and every config file in this course arrives as a dict. Lookup by key costs the same whether the dict holds ten items or ten million.
- set — you only care whether something is in there. A set has no order and no duplicates. Use it for "have I seen this id?" and for removing repeats in one call. The tour script builds
{"p50", "p95", "p50"}and gets two members, not three. - tuple — a record whose shape never changes. A point, a pair of return values, a row. Because it cannot change, it can be hashed, which is what lets a tuple be a dict key. Choosing one is a message to the next reader: this shape is fixed.
- list — everything else. Ordered, growable, duplicates welcome. It is the default, and the accented box says so. If you cannot answer yes to any of the three questions above, stop thinking and write a list.
The table below shows twelve lines you have not been taught yet. That is on purpose. Guess first, then check. Every line is explained in full over the next seven sections, and the step-by-step list above each script walks it again.
Step-by-step: what collections_tour.py does, in plain English
- Create one of each container: a
listof four strings (order kept, duplicates allowed), a two-numbertuple(fixed shape, cannot change), adictmapping percentile names to milliseconds, and asetwritten with three strings that collapses to two, because sets drop duplicates. - Append a fifth string to the list. Lists grow in place; nothing is copied.
- Print a slice,
values[1:3]: the items at positions 1 and 2. The stop position is not included, the same rule assubstring. - Print
values[-1]. A negative position counts from the end, so -1 is the last item. - Look up a key that does not exist with
.get("p99", 0). The second argument is the fallback, so the result is 0 and no error is raised. - Unpack the tuple into two names,
xandy, in one assignment. This is destructuring without the braces. - Unpack the list with a star:
headtakes the first item and*tailcollects everything else into a new list — a new object, in the sense drawn in Fig. A1.1b, not a window onto the old one. - Loop over six values and print whether each counts as true. Empty things and zero are false; a non-empty string, even
"0", is true. - Build two separate lists with equal contents and print two comparisons.
==asks whether the values match (True);isasks whether both names point at the same object (False).
# stdlib only -- run with: python3 collections_tour.py
values = ["p95", "p99", "p50", "p95"] # list: ordered, mutable, dupes ok
point = (3.5, 7.2) # tuple: fixed shape, immutable, hashable
latency_ms = {"p50": 210, "p95": 480} # dict: key -> value
seen = {"p50", "p95", "p50"} # set: dupes collapse -- len(seen) == 2
values.append("p999")
print(values[1:3]) # ['p99', 'p50'] slice = [start, stop) like substring
print(values[-1]) # p999 negatives count from the end
print(latency_ms.get("p99", 0)) # 0 lookup with default -- no KeyError
x, y = point # unpacking: destructuring without the braces
head, *tail = values # star scoops the rest, like JS ...rest
print(head, tail) # p95 ['p99', 'p50', 'p95', 'p999']
# Truthiness: EMPTY things are falsy ("", [], {}, 0, None). Non-empty is truthy.
for candidate in ("", [], {}, 0, None, "0"):
print(repr(candidate), "->", bool(candidate))
# '' -> False [] -> False {} -> False 0 -> False None -> False '0' -> True
# `is` compares IDENTITY (same object); == compares VALUE. Use `is` only for None.
a = [1, 2]; b = [1, 2]
print(a == b, a is b) # True False -- equal values, different objects
Two habits to install now. First, None is Python's null, and the
idiomatic check is x is None — identity, not equality — because None is a
singleton and == can be overridden by classes. Second, slicing (xs[2:5],
xs[-3:], xs[::2]) works on every sequence including strings; it always
returns a new object and never throws on out-of-range bounds. You'll slice constantly when
chunking documents in Module 08.
That second habit rests on the first, and the first is the most important picture on this
page. A name in Python does not hold a value. It holds an arrow to an object, and two names can
point at the same object. Everything below is drawn with the real output of
collections_tour.py and of the prediction exercise two blocks down.
- Equal is not the same. Two lists were built, each holding 1 and 2. The contents match, so
a == bis True. They are still two separate objects in memory, soa is bis False. This is exactly Java'sequalsagainst==, with the words swapped round, and it is why the only thing you should test withisisNone. - One object, two names.
alias = numscopies the arrow, not the list. Nowalias.append(4)reaches through the arrow and changes the object itself. Nothing happened to the namenums, yet printing it shows four items. Java and JavaScript behave the same way with objects; the surprise in Python is that a plain list is one. - Rebinding versus mutating.
alias = [9]looks like a change to the shared list and is not. It builds a new object and pointsaliasat it, leaving the old list exactly as it was. The rule that follows:name = somethingmoves an arrow, whilename.append(…),name[0] = …andname.sort()change the thing the arrow lands on.
Treat everything as an object.
Read a name as a pointer, not a box.
Expect assignment to rebind, never to copy.
Mutate through one name and every name sees it.
Ask is for identity and == for value.
Everything is an object: in Fig. A1.1b those are the boxes on the right, the
things that actually hold [1, 2, 3, 4]. A name is a pointer: the boxes on the left,
each with one arrow leaving it. Assignment rebinds: marker 3, where alias = [9]
moves a single arrow and leaves the old list untouched. Mutate through one name and every name
sees it: marker 2, where alias.append(4) changes the one object both names share.
Ask is for identity: marker 1, where two objects with equal contents print
True False.
- Two addresses for every item. The row above the boxes counts from the left, starting at 0. The row below counts from the right, starting at -1. They name the same seven items, so
xs[6]andxs[-1]both give 70. The negative row is what makes "the last three" a single expression,xs[-3:], with nolen()arithmetic. - Half-open, which is the part people get wrong. The two dashed lines are the cuts. The first cut is at position 1 and that item is taken; the second is at position 3 and that item is not. Subtracting gives the length straight away: 3 minus 1 is 2 items. Java's
substringand JavaScript'ssliceuse the same rule, so the arithmetic already lives in your fingers. - The three forgiving behaviours. A missing stop means "to the end". A stop past the end is clamped instead of raising, so
xs[5:100]is fine wheresubstringwould throw. A start already past the stop gives an empty list, again with no error. That forgiveness is why chunking a document in Module 08 needs no bounds checks.
Predict the output before running it — all three prints:
nums = [1, 2, 3]
alias = nums
alias.append(4)
first, *rest = nums
print(nums)
print(first, rest)
print(bool(""), bool([0]), bool("0"))
Reveal the answer
[1, 2, 3, 4] — assignment copies the reference, not the list, so
alias and nums are the same object: that is marker 2 of
Fig. A1.1b, drawn with these exact values (exactly like Java references).
Then 1 [2, 3, 4] — unpacking sees the already-mutated list.
Then False True True — the empty string is falsy, but [0] is a
non-empty list (truthy despite containing a falsy value) and "0" is a
non-empty string.
04 · Core PythonComprehensions, Iteration, and Generators
One of the five spellings in Fig. A1.0b was
{t.id: t.text for t in tickets}, and it is the one Marcus stared at longest. He knows
map. He knows filter. He had never seen them wearing one pair of brackets. This section takes that
spelling apart, then takes apart the machinery under it: the iteration protocol, and the generator,
which is how Module 06 streams tokens that do not exist yet. The habit being
replaced is make an empty list, loop, append, return.
Here's the syntax that made Marcus bounce, cured in one paragraph.
A comprehension is
filter + map read left to right: [x * 2 for x in xs if x > 0]
means "a list of x * 2, for each x in xs, if
x > 0".
Swap the brackets and you get the other collections:
{k: v for …} builds a dict, {x for …} builds a set.
Course code prefers
comprehensions over for-loop-and-append everywhere, for the same reason you prefer
xs.map(f) over a mutating loop: the intent is declared, not assembled — and there's no
accumulator variable to get wrong.
- The bracket says what you are building. Square brackets build a list, curly braces build a set, curly braces with a colon in the expression build a dict, and round brackets build a generator. On the loop side this is the
slow_ids = []line, the empty container you no longer have to create or name. - The expression, and the crossing arrow. This is what goes into each slot of the result, and its arrow lands on the last line of the loop, the
append. That crossing is the only real difference between the two sides. Read the expression first and you know what the line produces before you know where its data came from. - The loop clause. Same words as the plain
forline, minus the colon. The nametlives only inside the brackets and does not leak into the surrounding code, which is one fewer variable to accidentally reuse ten lines later. - The filter. Written last, executed first: items that fail it never reach the expression. It takes no
else, because anelsewould have to produce a value, and that belongs in the expression slot instead.
slow_ids = [1t["id"]2 for t in tickets3 if t["ms"] > 10004]
- The opening bracket. It says what you are building:
[makes a list. Swap it for{and you build a set, or a dict when the expression has a colon. Swap it for(and you build a generator, which computes nothing until asked. The common mistake is reading(x for x in xs)as a tuple. It is a generator, and it can be walked only once. - The expression. What goes into each slot of the result: here, the ticket's id. It runs once per item that survives the filter. Engineers from Java streams and SQL expect the "map" part to come last. In Python it comes first, and reading it first tells you what the line produces.
- The loop. Where the items come from and what each one is called.
tis a fresh name that exists only inside the brackets. It does not leak into the surrounding code, unlike the variable of a plainforloop. Two loops can be chained here, and they read left to right, outer loop first. - The condition. The filter, and it runs before the expression: only items that pass reach the front of the line. It takes no
else. If you need "this or that" per item, that is a conditional expression. It belongs in the expression slot:a if cond else b for t in tickets.
Step-by-step: what iteration_tour.py does, in plain English
- Define
tickets: a list of three dicts, each holding an id, a priority, and a duration in milliseconds. This is the shape of nearly every record you will meet in the course. - Build
slow_idswith a list comprehension: for each ticket, keep it only if its duration is over 1000 ms, and take its id. Result:['T-101']. - Build a dict from id to duration with a dict comprehension, and a set of the priorities with a set comprehension. Same shape, different brackets. The set has two members because duplicates collapse.
- Loop with
enumerate(tickets, start=1), which hands out a counter and the ticket together, so there is no index variable to maintain by hand. - Pair two parallel lists with
zipand turn the pairs into a dict.zipstops at the shorter list. - Sort the tickets by duration with
sorted(..., key=...). Thekeyfunction says what to compare; the original list is left untouched. Take the first result's id:T-103. - Define a generator,
read_percentiles: a function withyieldin it. Calling it runs none of its body; it returns an object that will run the body one step at a time, on demand. - Call
next()on it twice. Each call runs to the nextyield, hands out one value in seconds, and pauses. - Pass a fresh generator to
sum(). Any loop or aggregate consumes a generator to the end; the total is 5.53 seconds.
# stdlib only -- run with: python3 iteration_tour.py
tickets = [
{"id": "T-101", "priority": "high", "ms": 4200},
{"id": "T-102", "priority": "low", "ms": 950},
{"id": "T-103", "priority": "high", "ms": 380},
]
# list comprehension: filter + map in one readable pass
slow_ids = [t["id"] for t in tickets if t["ms"] > 1000]
print(slow_ids) # ['T-101']
# dict and set comprehensions -- same shape, different brackets
by_id = {t["id"]: t["ms"] for t in tickets}
levels = {t["priority"] for t in tickets}
print(by_id["T-103"], levels == {"high", "low"}) # 380 True
# enumerate and zip kill index bookkeeping -- you almost never write range(len(xs))
for i, t in enumerate(tickets, start=1):
print(i, t["id"]) # 1 T-101 / 2 T-102 / 3 T-103
names = ["p50", "p95"]; ms = [210, 480]
print(dict(zip(names, ms))) # {'p50': 210, 'p95': 480}
# sorted() is non-destructive and key= takes ANY function -- your comparator
print(sorted(tickets, key=lambda t: t["ms"])[0]["id"]) # T-103
# A generator computes values ON DEMAND -- `yield` pauses, next() resumes
def read_percentiles(rows):
for row in rows:
yield row["ms"] / 1000 # seconds; nothing runs until asked
gen = read_percentiles(tickets)
print(next(gen), next(gen)) # 4.2 0.95
print(sum(read_percentiles(tickets))) # 5.53 -- any loop/sum consumes a generator
The mechanism underneath all of this is the iteration protocol: anything
with __iter__ can be looped, summed, unpacked, or comprehended — lists, dicts (keys),
files (lines), and generators all speak it. A generator is a function with
yield in it: calling it runs no code; each next() runs to the
next yield, hands the value out, and freezes the function's locals mid-flight. It's
C#'s yield return, JS's function*. Why care? Memory: a list of a billion
rows must exist all at once; a generator holds one row at a time. Streaming LLM tokens in Module 06
is exactly this shape.
- The pull. Nothing happens until a consumer asks. A
forloop, asum, alist(…)call: all of them are justnext()in a loop. This is the reverse of the arrangement you are used to, where the producer fills a collection and hands the whole thing over. - The pause. The generator runs to its
yield, hands out one value, and stops there with its local variables and its position in the loop still alive. The nextnext()resumes on the line after theyield. Nothing polls, nothing blocks; the function is simply frozen between calls. - The list version. Eight boxes, all of them built before the consumer looks at the first one. With a million rows those boxes are a million objects, which is the arithmetic the pencil exercise above works out in bytes.
- The generator version. One box, reused. That is what "constant memory" means, and it is why a generator can stand in front of a 10 GB file or a model that is still producing its answer one token at a time.
Those two answers are worth one picture each, because they are the two facts that decide which one you reach for. The first is a size. The second is what happens on the second pass.
- Why the list bar is in two pieces. The left piece is the list itself, 8,448,728 bytes of slots, which is the number
sys.getsizeofreports. The right piece is the million integer objects those slots point at, 28 bytes each. The list does not contain the integers; it contains arrows to them, which is Fig. A1.1b again, a million times over. - Why the generator bar is invisible. 200 bytes is the whole generator object: the frozen frame, the position, nothing else. Against 36 MB on the same scale it is four thousandths of a pixel, so it is drawn at 3 pixels as a courtesy. The ratio is about 180,000 to 1, and it grows with the input, because the generator's size does not.
- The price, drawn as a tape. The first
sumpulls all million values and leaves the read head at the end. The secondsumstarts from where the head is, finds nothing, and returns the sum of nothing, which is 0. That is the failure the fireside chat in section 10 argues about, and the reason "walk it twice" means "make it a list".
Predict the exact output, including the order of the first two lines:
def countdown(n):
print("starting")
while n:
yield n
n -= 1
c = countdown(3)
print("created")
print(next(c))
print(next(c))
Reveal the answer
created, then starting, then 3, then 2.
The surprise is the order: calling countdown(3) runs zero lines of its
body — it just builds the generator object. The body (including that first
print) only starts on the first next(), runs to yield n,
and freezes. The second next() resumes after the yield, decrements, loops
back, yields 2. If your mental model was "functions run when called", generators are the one
place Python breaks it.
05 · Core PythonFunctions Properly — Up To and Including Decorators
Two of Marcus's five spellings are now dealt with. The line he bounced off was a
function signature, and the libraries in this course are built almost entirely out of that one
shape. The habit being replaced is method overloading and builder objects: Python gives you
defaults and named arguments instead, which is why every LLM call in later modules reads like a
block of configuration. The same two features are also what make the @ line on every
test fixture, tool and route a plain ten-line function rather than framework magic.
Python functions have three calling-convention features you will meet on page one of every AI library.
- Defaults —
size=500. - Keyword arguments — callers write
chunk(text, overlap=0). Self-documenting call sites, and the reason LLM SDK calls read like config. - The catch-alls
*argsand**kwargs— "any positional args as a tuple, any keyword args as a dict".
The catch-alls look academic until you realise they are the fuel for the single most important pattern in this course's toolchain: the decorator.
Step-by-step: what functions_tour.py does, in plain English
- Bring in
functoolsandtimefrom the standard library. This script never calls them; they are the importstimed.py, the next file, builds on. - Define
chunkwith two defaulted parameters,size=500andoverlap=50. The body computes a step and returns a list of slices of the text, one per step, using a comprehension overrange. - Call it on a 2000-character string with the defaults: a step of 450 gives 5 chunks. Call it again overriding only
overlapby name: a step of 500 gives 4. Naming the argument is what lets you skip the one in the middle. - Define
debug_call(*args, **kwargs). The star collects any positional arguments into a tuple; the double star collects any named arguments into a dict. Call it with two numbers and one named value, and print both containers. - Define
shoutas a one-line function, then put three callables in a list:shout, the built-in methodstr.strip, and alambdathat keeps the first ten characters. Functions are values, so a list can hold them. - Loop over the list and apply each function to the text in turn, feeding each result into the next. Print the final string with
reprso the quotes make the trimmed whitespace visible.
# stdlib only -- run with: python3 functions_tour.py
import functools
import time
# Defaults + keyword args: callers name what they override.
def chunk(text: str, size: int = 500, overlap: int = 50) -> list[str]:
step = size - overlap
return [text[i:i + size] for i in range(0, len(text), step)]
print(len(chunk("x" * 2000))) # 5
print(len(chunk("x" * 2000, overlap=0))) # 4 -- override one arg by name
# *args / **kwargs: accept anything, forward everything.
def debug_call(*args, **kwargs):
print("args:", args, "kwargs:", kwargs)
debug_call(1, 2, model="small") # args: (1, 2) kwargs: {'model': 'small'}
# Functions are values: store them, pass them, return them.
def shout(s: str) -> str: return s.upper()
transforms = [shout, str.strip, lambda s: s[:10]] # lambda: one-expression fn
text = " hello, python "
for fn in transforms:
text = fn(text)
print(repr(text)) # 'HELLO, PYT'
Now the payoff. A decorator is nothing but a function that takes a
function and returns a wrapped version — the same higher-order move as Express middleware or a Java
dynamic proxy. The @name line is pure sugar: @timed above
def slow_sum means exactly slow_sum = timed(slow_sum). Here's a complete,
useful one in ten lines:
Step-by-step: what timed.py does, in plain English
- Import
functoolsfor thewrapshelper andtimefor a high-resolution clock. - Define
timed(fn): a function that takes a function. Everything it does is build and return a replacement. - Inside it, define
wrapper(*args, **kwargs). The catch-alls mean the wrapper accepts whatever the original accepted, without knowing its signature.@functools.wraps(fn)copies the original's name and docstring onto the wrapper, so tracebacks and help text still sayslow_sum. - The wrapper's body reads the clock, calls the original with every argument forwarded, reads the clock again, prints the difference in milliseconds, and returns the original's result unchanged.
- Return the wrapper. It keeps a reference to
fnaftertimedhas finished; that captured variable is what makes it a closure. - Write
@timedabovedef slow_sum. That single line meansslow_sum = timed(slow_sum): the name now points at the wrapper. - Call
slow_sum(1_000_000). The wrapper runs, times the real sum of squares, prints the duration, and hands back the total.
# stdlib only -- run with: python3 timed.py
import functools
import time
def timed(fn):
"""Wrap fn so every call reports its duration."""
@functools.wraps(fn) # keep fn's real name/docstring
def wrapper(*args, **kwargs): # accept anything...
start = time.perf_counter()
result = fn(*args, **kwargs) # ...forward everything
ms = (time.perf_counter() - start) * 1000
print(f"{fn.__name__}: {ms:.1f} ms")
return result
return wrapper # wrapper CLOSES OVER fn -- a closure
@timed # sugar for: slow_sum = timed(slow_sum)
def slow_sum(n: int) -> int:
return sum(i * i for i in range(n))
print(slow_sum(1_000_000))
# slow_sum: 61.0 ms (your number will vary)
# 333332833333500000
@timed makes the name slow_sum point at a wrapper that calls the original and times it.- Before. One name, one function object. Nothing unusual, and this is still how every undecorated function on this page sits in memory.
- After.
timedwas handed the original and returned a different function. The@line then pointed the old name at that new function. This is the same arrow-moving from Fig. A1.1b, marker 3, applied to a function instead of a list. The dashed arrow is the closure: the wrapper kept a private reference to the original, which is the only thing that can still reach it. - The call, step by step. Callers still write
slow_sum(1_000_000)and still get333332833333500000back. The four steps happen around that, not inside it. Because the wrapper takes*args, **kwargs, it can wrap a function of any signature without knowing one thing about it, and that is why the same ten lines work as a test fixture, an MCP tool and a web route.
Note the closure: wrapper keeps using fn long after timed
returned — same lexical capture as a JS closure. This ten-line shape is not a curiosity; it's how
half the course's tools present themselves. @pytest.fixture (Module 07),
@mcp.tool (Module 10), and @app.post("/summarize") (Module 12, FastAPI)
are all "function in, registered/wrapped function out". After today, you'll read them as plumbing,
not magic. On lambda: it's for one-expression throwaways — key=lambda t:
t["ms"] is its natural habitat. The moment logic needs two steps or a name, use
def.
Questions you might be asking now
Fig. A1.2c says a call forwards every argument and a decorator is one rebinding. For an engineer arriving from Java or TypeScript, that raises two questions: what exactly does a function receive, and what runs when. Every answer below uses the same three tickets from iteration_tour.py.
| Ticket | priority | ms | As the program writes it |
|---|---|---|---|
| T-101 | high | 4,200 | {"id": "T-101", "priority": "high", "ms": 4200} |
| T-102 | low | 950 | {"id": "T-102", "priority": "low", "ms": 950} |
| T-103 | high | 380 | {"id": "T-103", "priority": "high", "ms": 380} |
When I pass tickets into a function, does the function get a copy or the original? Is Python pass-by-reference or pass-by-value?
Neither, in the sense C++ gives those words. The parameter becomes a second name for the very same list, exactly like passing an object in Java or JavaScript. So queue.append(…) inside the function grew the caller's list from 3 tickets to 4, while queue = [] inside the function changed nothing outside it.
The Python documentation's own phrase is that arguments are passed by assignment. A call does exactly what an = does. Calling escalate(tickets) runs queue = tickets as the function starts. And the rebinding rule from Fig. A1.1b already told you what = does: it copies an arrow, never an object.
The script passing_and_rebinding.py makes the arrows visible. It gives every object it meets a short label: L1 for the first list, D1 for the first dict, I1 for the first int. Raw id() numbers are memory addresses that change on every run, so the labels are easier to read. Same label means same object.
| Call | The function body does | Inside the function | Back in the caller |
|---|---|---|---|
escalate(tickets) | queue.append(T104) | queue → L1; queue is tickets is True | tickets → L1, now 4 tickets |
clear(tickets) | queue = [] | queue → L2, 0 tickets | tickets → L1, still 4 tickets |
bump(first_ms) | ms += 100 | ms was I1 (4200), now I2 (4300) | first_ms → I1, still 4200 |
mark_urgent(tickets[1]) | ticket["priority"] = "urgent" | ticket → D1 | tickets[1] → D1, priority now 'urgent' |
Read the four rows as two rules:
- Change the object, and the caller sees it. Rows 1 and 4 reach through the arrow and change what it lands on.
append, item assignment andsort()all work this way. - Rebind the name, and the caller does not. Rows 2 and 3 point the function's own name at a different object. The caller's name is a separate arrow, and nothing moved it.
- A second arrow, not a copy. Starting the call ran
queue = tickets, so both names land on L1. That is whyqueue is ticketsprinted True inside the function.queue.append(T104)changed the object itself, so the caller sees 4 tickets without ever touching its own name. - Rebinding stays inside.
queue = []built a new list, L2, and moved only the function's arrow. The caller's arrow never moved, soticketsstill lands on L1 with its 4 tickets. Whenclearreturns, nothing points at L2 any more, and Python frees it. - An int looks copied, and is not. An int object cannot be changed, so
ms += 100has nothing to grow. It builds I2, holding 4300, and moves the function's arrow to it; the dashed line is where that arrow started. The caller'sfirst_msstill lands on I1, holding 4200.
Now the words themselves. People use "by reference" for two different behaviours, and only one of them exists in Python:
| Passing… | The function mutates it (append) | The function assigns to its parameter (= []) |
|---|---|---|
| An object in Java | Caller sees the change | Caller sees nothing |
| An object or array in JavaScript or TypeScript | Caller sees the change | Caller sees nothing |
| Anything at all in Python | Caller sees the change | Caller sees nothing |
A variable in C# with ref, or in C++ with & | Caller sees the change | Caller sees it too: this is true pass-by-reference |
So Python behaves exactly as Java does for objects, with one simplification. In Python everything is an object, so there is no second rule for primitives. An int is simply an object nobody can change, which is why row 3 of the first table looks like Java copying an int. Nothing was copied there; a new int was built.
The honest limit cuts both ways. There is no way to write a Python function that rebinds the caller's variable, the way C# ref can. A function that makes a new list must return it, and the caller writes tickets = clear(tickets). And nothing stops a function from mutating what you pass in.
If you need the original kept safe, pass a copy: escalate(list(tickets)). Remember Gotcha 3 in section 10, though. list(…) copies only the outer list, so mark_urgent on that copy would still change the three shared dicts.
A call runs parameter = argument. The function gets a second arrow to your object: mutations are shared, rebinding is private, and nothing is ever copied.
Inside a function, queue += [t] changed my list, but queue = queue + [t] did not. Aren't those the same line?
No. On a list, += means "extend this very object", so every name that points at it sees the new ticket. queue + [t] builds a brand-new list, and the = points only the function's name at it. Measured: after += the caller still had list L3, now with 4 tickets; after = … + the caller still had list L4 with 3.
In Java or TypeScript, x += y is shorthand for x = x + y, full stop. Python lets each type decide what += means. A list defines its own in-place version; an int, a string and a tuple do not. Here is what Python does with queue += [T104], in order:
- Ask the object first. Python looks for an in-place add on the object
queuepoints at. A list has one, a method called__iadd__. - Extend in place. The list's
__iadd__appends the new ticket to L3 itself, then returns L3. - Assign the result back. Python runs
queue =whatever step B returned. That is L3 again, so the arrow lands where it already was. - The fallback for types that cannot change. An int, a str or a tuple has no in-place add. Python uses the plain
+instead, which builds a new object, and step C moves the arrow to it.
add_in_place: queue += [T104] | add_by_copy: queue = queue + [T104] | |
|---|---|---|
| Caller's list before the call | L3, 3 tickets, slots D2 D3 D4 | L4, 3 tickets, slots D5 D6 D7 |
queue after the line | L3, the same object, 4 tickets | L5, a new object, 4 tickets |
| What the new ticket went into | A fourth slot on L3 | L5's slots: D5 D6 D7 D8, the three old dicts plus T-104 |
| Caller's list after the call | L3, 4 tickets | L4, still 3 tickets |
| Pointers copied | 1 | 4: the 3 already there, plus the new one |
- One object, one more slot.
+=asked L3 to extend itself, so the new ticket landed in a fourth slot of the list both names already shared. Then the name was assigned back to the same L3. One pointer was copied, and the caller'sticketshas 4 tickets. - A new object, and only one name moved.
queue + [T104]built L5 and filled it with arrows to the three existing dicts plus T-104. The dicts were not copied, only the arrows to them. Then=moved the function's name to L5, and the caller's L4 kept its 3 tickets. - The copying adds up. In a loop,
queue = queue + [t]copies every pointer already in the list, every time. For 20,000 tickets that is 0 + 1 + 2 + … + 19,999 = 199,990,000 pointer copies. That took 397.7 ms of CPU time here, against 1.87 ms for+=. Double the tickets and the copying roughly quadruples, while+=only doubles.
| Type | Line | alias is value afterwards | alias | value |
|---|---|---|---|---|
| list | ["T-101"] += ["T-102"] | True | ['T-101', 'T-102'] | ['T-101', 'T-102'] |
| int | 4200 += 100 | False | 4200 | 4300 |
| str | "T-10" += "1" | False | 'T-10' | 'T-101' |
| tuple | ("T-101",) += ("T-102",) | False | ('T-101',) | ('T-101', 'T-102') |
One well-known oddity proves that steps B and C really are two separate steps. Put a list inside a tuple, then use += on it: pair = (["T-101"], 4200), then pair[0] += ["T-102"].
The line raised TypeError: 'tuple' object does not support item assignment. Yet printing pair afterwards showed (['T-101', 'T-102'], 4200). Step B extended the list, which is allowed. Step C then tried to store the result back into slot 0 of the tuple, which a tuple forbids. The official Python FAQ lists this exact case.
The difference also has a price, drawn in marker 3 of Fig. A1.2j. queue = queue + [t] copies every pointer the list already holds.
Build a queue of n tickets one at a time that way, and the copies add up. The total is 0 + 1 + 2 + … + (n − 1), which is n × (n − 1) ÷ 2. For 20,000 tickets that is 199,990,000 copies.
Measured in CPU time on one machine, that loop took 397.7 ms, against 1.87 ms with +=: about 212 times longer. Your numbers will differ; the shape will not. Doubling the queue multiplied the slow loop's time by about 4 and the fast loop's by about 2.
For one call on three tickets, neither line costs anything you could measure. So choose by meaning, not speed. Use += or append when every holder of the list should see the new ticket. Use + when you want a new list and the caller's list left alone.
On a list, += changes the object every name shares, while x = x + y builds a new object and moves one name. On an int, a str or a tuple, += can only do the second.
Walk one call through @timed, line by line. What runs when the file loads, and what runs when I call the function?
Two separate moments. When Python reaches @timed and the def under it, it calls timed once, builds the wrapper and points the name at it; nothing is timed yet. Every later call runs only the wrapper, which calls your original function once, in the middle. Counted over two calls: timed ran 1 time, the wrapper 2 times, the original 2 times.
Fig. A1.2c drew what one call does. The missing piece is when each line runs. In Java, an annotation is metadata that some framework reads later. A Python decorator is ordinary code, and it runs at a moment you can print.
The script decorator_timeline.py is timed.py from the page with a numbered log line at each moment. It decorates total_ms(rows), which adds up the ms field of every ticket it is given. Then it calls it twice: once on the 300,000-slot queue, once on the three tickets.
| Step | Printed by the script | What is happening |
|---|---|---|
| 1 | file loads: the def timed line runs | def creates a function object named timed. None of its body runs. |
| 2 | file loads: reached @timed and the def under it | Python builds the plain total_ms function object first. |
| 3 | timed() runs, handed the function object 'total_ms' | The @ line calls timed(total_ms). This is the only time timed ever runs. |
| 4 | timed() returns the wrapper; the @ line points the name at it | total_ms = timed(total_ms) is now complete. |
| 5 | name total_ms -> a function whose code is 'wrapper', __name__ still says 'total_ms' | functools.wraps copied the name across, not the code. |
| 6 to 9 | call 1: total_ms(queue) … total_ms: 8.8 ms … call 1 returned 553,000,000 | The wrapper ran around the original: clock, call, clock, print, return. |
| 10 to 13 | call 2: total_ms(tickets) … total_ms: 0.0 ms … call 2 returned 5,530 | The same wrapper again. timed did not run again. |
Now zoom into call 1, the steps inside the wrapper, one line at a time:
- The name leads to the wrapper.
total_ms(queue)looks uptotal_msand finds the wrapper.*argscollects(queue,)and**kwargscollects an empty dict. - Read the clock.
start = time.perf_counter(). - Call the original.
fn(*args, **kwargs)unpacks back intofn(queue).fnis your originaltotal_ms, kept by the closure. It adds 300,000 ms values: 5,530 × 100,000 = 553,000,000. - Read the clock again, and print. 8.782 ms had passed, printed rounded as
total_ms: 8.8 ms. That is wall-clock time on one machine; yours will differ. - Return the original's result unchanged. The caller receives 553,000,000 and cannot tell a wrapper was involved.
- Once, at definition. Steps 1 to 5 of the log. The
@line waits for thedefunder it to build your function, callstimedwith it, then points the name at whatevertimedreturned. Nothing is timed here. Had this file been imported rather than run, all of this would happen during the import. - Call 1, around your code. The caller wrote
total_ms(queue)and reached the wrapper. The wrapper's four lines ran in order. Only the green box is your original function, reached through the closure. It returned 553,000,000, and the wrapper passed that on untouched. - Call 2, the same wrapper. Three tickets instead of 300,000, so the clock read 0.0053 ms and printed 0.0 ms. The shape is identical: the wrapper ran again, the original ran again, and
timeddid not. The counter line at the bottom confirms it.
Two things follow from the timeline, and both matter in later modules:
- Decorators run when the file is imported. An import runs a file top to bottom, as section 08 showed, so every
@line in it runs its decorator right then. That is how@mcp.toolin Module 10 and@app.postin Module 12 register a function before anyone calls it. It is also why a slow decorator makes an import slow. - Stacked decorators apply from the bottom up.
@aabove@babovedef fmeansf = a(b(f)).bwraps your function first, andawraps whatbreturned.
The honest limit is in step 5. functools.wraps copies the name, the docstring and a few other attributes onto the wrapper. It also stores your original as total_ms.__wrapped__. It does not make them the same function: the code behind the name is still the wrapper's, which is what step 5 printed.
@timed runs once, when the def runs, and rebinds the name. Every call after that runs the wrapper, which calls your original in the middle.
What if I put @timed on a generator function? Does it time the work?
No. Calling a generator function runs none of its body, so the wrapper times only the creation of a generator object, and prints slow_ids: 0.0 ms. The real work, checking 300,000 slots for slow tickets, happens later, when something pulls the values. Measured: the decorator saw 0.0019 ms; the pull took 9.4 ms, and nothing timed it.
This is the countdown prediction from section 04 meeting the decorator from Fig. A1.2k. Calling countdown(3) printed nothing, because a function with yield in it hands back a generator object and runs no body lines. The wrapper's clock sits around exactly that call.
The script decorator_timeline.py puts @timed on slow_ids(rows), a generator that walks the rows and yields the id of every ticket slower than 1,000 ms. Then it runs gen = slow_ids(queue) and, on a later line, list(gen). In order:
- The call reaches the wrapper. Log steps 3 and 4. The wrapper reads the clock and calls the original with
queue. - The original returns at once. Calling a generator function builds a generator object: the rows, plus a paused position at the top of the body. Not one ticket is checked.
- The wrapper stops the clock and prints. Log step 5:
slow_ids: 0.0 ms. The raw reading was 0.0019 ms, the cost of building one small object. - The caller now holds the generator. Log step 6. The wrapper has returned; its clock is gone for good.
list(gen)pulls every value. Log steps 7 to 9. Only now does the body run: 300,000 slots checked, 100,000 ids yielded, 9.4 ms, with no clock running.
total_ms, an ordinary function | slow_ids, a generator function | |
|---|---|---|
What fn(*args, **kwargs) returns | The answer, 553,000,000 | A generator object, with no work done |
| When the body runs | Inside the wrapper, between the two clock readings | Later, wherever the values are pulled |
| What the clock measured | The work: 8.782 ms | Building one object: 0.0019 ms |
| What it printed | total_ms: 8.8 ms | slow_ids: 0.0 ms |
To time the work, the clock has to run while the values are pulled. The script's fix is timed_gen, a wrapper that is itself a generator. Its body is yield from fn(*args, **kwargs) inside a try, with the clock read before it and again in the finally. yield from hands on each value the original yields, one at a time, as the consumer asks.
| Job | timed | timed_gen |
|---|---|---|
| Start the clock | Before calling fn | On the first next(), when the wrapper's own body starts |
| Run the work | result = fn(*args, **kwargs) | yield from fn(*args, **kwargs): pass on each value as it is pulled |
| Stop the clock | Right after fn returns | In finally:, after the last value, or when the consumer stops early |
| Printed for the 300,000-slot queue | 0.0 ms | 10.2 ms |
- The clock stops before the work starts. The red sliver is the wrapper's whole clock window: 0.0019 ms, the time it takes to build a generator object. The grey bar is the real work, done afterwards by
list(gen)while no clock was running. timed.py reports what it saw, and it saw almost nothing. - A clock around the pull.
timed_gen's wrapper is a generator too, so its clock starts at the firstnext()and stops in itsfinallyafter the last value. The bracket now spans the pull: 10.2 ms, close to the 9.4 ms of row 1's untimed bar. This is the number you wanted. - The consumer is inside the window. The same generator yielded the same 100,000 ids. The loop pulling them did a little extra work per id, and the clock read 48.6 ms. The clock measures from the first value to the last, and the consumer's work in between counts.
Marker 3 is the honest limit of the fix. timed_gen measures wall time from the first value to the last, not the generator's own work. Use it to answer "how long did this stream take", not "how slow is this generator".
The same trap waits in Module 01 and Module 06. Calling an async def function also returns at once, with a coroutine object instead of a generator. decorator_timeline.py put @timed on one that awaits a 50 ms sleep. The decorator printed fetch_ticket: 0.0 ms, and awaiting the coroutine took 50.7 ms. Timing async code needs an async def wrapper that awaits the original.
A decorator times the call, and calling a generator or an async function does no work yet. Time the consumption instead: wrap with yield from, or await inside an async wrapper.
The * in a signature makes everything after it keyword-only. Predict what happens:
def greet(name, *, loud=False):
return name.upper() if loud else name
print(greet("Ada", True))
Reveal the answer
TypeError: greet() takes 1 positional argument but 2 were given. The bare
* is a fence: loud can only be passed as
greet("Ada", loud=True). Library authors use this deliberately so call sites stay
readable — you'll see keyword-only params throughout the OpenAI and Anthropic SDKs, which is
why their calls look like create(model=…, max_tokens=…, messages=…).
06 · Core PythonClasses, Dataclasses, and Why the Course Mostly Uses Pydantic
Marcus writes classes all day, so this part transfers almost intact. What does
not transfer is how many of them he needs, and how much of each he has to type. Two surprises
first, both cosmetic, then the thing course code actually uses: a decorator that writes the
constructor, the printer and the equality check from a list of typed fields. The habit being
replaced is the deep hierarchy with hand-written getters and an equals you hope
somebody kept in step with the fields.
Python classes hold two surprises for Java/TS refugees, both cosmetic. First,
__init__ is the constructor (the double underscores — "dunders" — mark methods Python
itself calls). Second, self is just this made explicit: it's the first
parameter of every method, filled in automatically when you call obj.method(). That's
genuinely the whole trick — methods are ordinary functions stored on a class.
Step-by-step: what classes_tour.py does, in plain English
- Import
dataclassandfieldfrom the standard library. - Define
Ticketthe manual way.__init__is the constructor;selfis the instance being built, passed in automatically. Each assignment toself.somethingcreates an attribute. - Build a ticket and print its two attributes. Then compare two tickets built from the same values: the result is False, because a plain class compares by identity unless you write
__eq__yourself. - Define
Cardwith@dataclass. The class body is a list of fields with type hints; the decorator writes__init__,__repr__and__eq__from that list. - Give
streaka default of 0 andtagsa default offield(default_factory=list). The factory builds a fresh list per instance; a bare[]would be shared by every card, which is the trap in section 10. - Add a
@propertynamedmastered. It is a method that reads like an attribute:c.mastered, with no parentheses, runs it and returns True once the streak reaches 3. - Build a card and print it: the generated
__repr__shows every field. Compare it with an identical card: True, because the generated__eq__compares field by field. - Set the streak to 3 and read
mastered: True.
# stdlib only -- run with: python3 classes_tour.py
from dataclasses import dataclass, field
# The manual way -- fine, but boilerplate you'll stop writing today.
class Ticket:
def __init__(self, id: str, priority: str = "low") -> None:
self.id = id
self.priority = priority
t = Ticket("T-101", "high")
print(t.id, t.priority) # T-101 high
print(Ticket("T-1") == Ticket("T-1")) # False -- default == is identity!
# @dataclass generates __init__, __repr__, __eq__ from the field list.
@dataclass
class Card:
front: str
back: str
streak: int = 0
tags: list[str] = field(default_factory=list) # why not []? See "Watch it break"
@property
def mastered(self) -> bool: # computed attribute -- read without ()
return self.streak >= 3
c = Card("What does `is` compare?", "Object identity")
print(c) # Card(front='What does `is` compare?', back='Object identity', streak=0, tags=[])
print(c == Card("What does `is` compare?", "Object identity")) # True -- by value now
c.streak = 3
print(c.mastered) # True
@dataclass reads the typed field list and writes three methods, which is why the same two cards now compare True instead of False.- The field list is the input. Four lines, each a name and a type, two of them with defaults. That list is the only thing the decorator reads. Add a field and all three generated methods change with it, which is the part a hand-written
equalsalways eventually forgets. - The three methods are the output. A constructor in field order, a printer that names every field, and an equality test that compares them one by one. They are ordinary methods on an ordinary class; nothing dynamic happens at call time.
- Why the two results differ. A plain class has no idea what "equal" should mean, so Python falls back to "is it the very same object", which is Fig. A1.1b marker 1 all over again, and two separately built tickets are never the same object. The dataclass supplies the missing definition. The
default_factoryline on the last field exists for the trap in section 10: a bare[]there would be one list shared by every card ever made.
The idiom this course lives by: data first, inheritance rarely. Modern
Python (and modern AI code in particular) models the domain as typed records — dataclasses — plus
plain functions that transform them. Deep class hierarchies are as rare in 2026 Python as they are
in modern TypeScript. You'll see exactly one upgrade beyond @dataclass in this course:
Pydantic models (Module 01), which look nearly identical but validate at
runtime — feed one malformed JSON and it raises a precise error instead of storing garbage.
Dataclasses trust their caller; Pydantic checks the border. Course rule of thumb: dataclass for
internal state, Pydantic wherever data crosses a boundary — API responses, LLM structured outputs,
config files.
Predict both prints:
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
p, q = Point(1, 2), Point(1, 2)
print(p == q)
print(p is q)
Reveal the answer
True then False. @dataclass generated an
__eq__ that compares field-by-field, so == is value equality — but
they're still two distinct objects, so is (identity) is False. A
plain class without @dataclass would print False False: default
== falls back to identity, exactly like Java's == on objects.
07 · Core PythonErrors & Files — EAFP, raise, and What with Actually Does
Every tour script so far has assumed that nothing goes wrong. Marcus's instinct
is to check first: does the file exist, is this string a number, is the key present. Python's
instinct is the opposite, and it is not laziness. A pre-check races, because the file can vanish
between the check and the open. The habit being replaced is look-before-you-leap, and what replaces
it is try the real thing and catch the one failure you can name. The section ends on
with, which gives him the same guarantee try-with-resources already gives him today.
Python's error culture differs from Java's in philosophy, not machinery. The community idiom is EAFP — "easier to ask forgiveness than permission": try the happy path and catch the specific failure, rather than pre-checking every condition (LBYL, "look before you leap").
EAFP wins in Python because exceptions are cheap, and
because pre-checks race: the file you os.path.exists()-checked can vanish before you
open it.
The full statement has four clauses — try / except /
else (runs only if nothing was raised) / finally (runs no matter
what):
Step-by-step: what errors_tour.py does, in plain English
- Import
jsonandPath. Then write a small JSON file,deck.json, so the script has something real to load. - Define
load_deck(path). Thetrybody holds only the two lines that can fail: reading the file and parsing the text. - First
except: if the file is missing, return an empty deck. A missing file is a normal state here, not a bug. - Second
except: if the text is not valid JSON, raise aValueErrorthat names the file.from errattaches the original parse error, so the traceback shows both. elseruns only when nothing was raised: return the parsed deck. Keeping the return out of thetrybody means a bug in it cannot be mistaken for a file error.finallyruns on every path, success or failure, and prints a line. This is where cleanup goes.- Call the function on the real file and print the first card's front; then call it on a missing file and see the empty deck. Both print "load attempted" first.
- Open the file with
with. Entering the block calls the file's__enter__; leaving it, even by an exception, calls__exit__, which closes the file. Print the length of its contents. - Delete the demo file with
unlink().
# stdlib only -- run with: python3 errors_tour.py
import json
from pathlib import Path
deck_file = Path("deck.json")
deck_file.write_text(json.dumps({"cards": [{"front": "EAFP?", "back": "Ask forgiveness"}]}))
def load_deck(path: Path) -> dict:
try:
raw = path.read_text() # may raise FileNotFoundError
deck = json.loads(raw) # may raise json.JSONDecodeError
except FileNotFoundError:
return {"cards": []} # a missing deck is just an empty deck
except json.JSONDecodeError as err:
# Re-raise as OUR error; `from err` chains the original traceback.
raise ValueError(f"{path} is corrupt: {err}") from err
else:
return deck # only reached if nothing raised
finally:
print("load attempted") # cleanup line: runs on every path
print(load_deck(deck_file)["cards"][0]["front"])
# load attempted
# EAFP?
print(load_deck(Path("missing.json")))
# load attempted
# {'cards': []}
# `with` = a try/finally you can't forget. Entering calls __enter__,
# leaving calls __exit__ (close/release/rollback) -- even if the body raises.
with deck_file.open() as f:
print(len(f.read())) # 58
deck_file.unlink() # tidy up the demo file
finally is on both routes, which is why "load attempted" is printed twice.- The column is the statement. Read it top to bottom: the risky lines, then one handler per failure you can name, then the clause for "it all worked", then the clause that runs whatever happened. Only the two risky lines are inside
try. That is deliberate: if the return statement were in there, a bug in it would be caught by your file handler and reported as a file problem. - Run A, the left rail. The file exists and the JSON parses, so neither handler is entered,
elsereturns the deck, andfinallyprints. Notice the order in the output: "load attempted" appears before the card's text, becausefinallyruns on the way out of the function, before the caller'sprintgets the value. - Run B, the right rail.
read_textraises, so the rest of thetrybody is abandoned mid-flight, the matching handler returns an empty deck, andelsenever runs.finallystill prints. Swap the file for corrupt text and the second handler runs instead, raising aValueErrorthat names the file whilefrom errkeeps the original parse error in the traceback.
Three rules of raising well: catch the narrowest exception you can name (bare
except: hides bugs and eats Ctrl-C); raise types that tell the caller
what to do (ValueError for bad input, custom exceptions for domain failures); and
chain with raise … from err so the original cause survives in the traceback. And for
files: it's pathlib.Path everywhere in this course — path.read_text(),
path.write_text(), path / "subdir" / "file.json" — the
object-oriented API that replaced the os.path string-mangling era. A
context manager (the thing with drives) is any object with
__enter__/__exit__; it's C#'s using, Java's
try-with-resources. Module 06 streams LLM responses inside a with block for exactly
this guarantee: the connection closes even when your code throws mid-stream.
Which lines print, in what order?
try:
x = int("42")
except ValueError:
print("bad")
else:
print("good", x)
finally:
print("done")
Reveal the answer
good 42 then done. int("42") succeeds, so
except is skipped and else runs — else exists so you can
keep the try body down to the one risky line, with the follow-on code outside the
blast radius. finally runs on success, failure, even on return.
Change "42" to "forty-two" and you'd get bad then
done.
08 · Core PythonModules, __main__, and a Ten-Line Preview of uv
Six hours was the promise, and about here Marcus wants to know where the code
lives and how the dependencies get installed. A Python file is a module, and importing it runs it,
which is the fact behind the odd-looking line at the bottom of every script on this page. Then the
part his package.json instincts already cover: a project file, a lock file and a
per-project interpreter. The habit being replaced is one machine-wide Python with a pile of
pip install in it.
A Python module is just a file — importing it executes it top to bottom, once, and
caches the result in sys.modules (so a second import is a cheap dict lookup, like
Node's require cache). A package is a directory of modules. from metrics import p95
is your named import; import metrics then metrics.p95(…) is your
namespace import. Because importing runs the file, every script you'll see in this course guards
its entry point:
Step-by-step: what metrics.py does, in plain English
- Define
p95: sort a copy of the list and return the value 95% of the way along it. This is the reusable part, and the reason another file would import this one. - Check
__name__. Python sets this variable to the string"__main__"only in the file it was asked to run; in an imported file it holds the module's own name,"metrics". - If the check passes, run a self-test and print the result. Under
import metricsthe check fails and this block is skipped, so importing the module has no side effects.
# A module IS a file. Run directly: python3 metrics.py -> self-test runs.
# Import from elsewhere: `import metrics` -> self-test does NOT run.
def p95(xs: list[float]) -> float:
return sorted(xs)[int(len(xs) * 0.95)]
if __name__ == "__main__":
# __name__ is "__main__" only when THIS file is the program being run;
# under import, it's the module's own name ("metrics").
print("self-test:", p95(list(range(100))) == 95) # self-test: True
Environments: Python's answer to node_modules is the virtual environment — a
per-project interpreter + packages directory. The historical pain (venv activation dances,
requirements.txt drift) is over; the 2026 tool is uv, and Module 01
sets it up properly. Ten-line preview so it isn't a surprise:
You are not expected to run or memorise the commands below yet. They are here so the shape of a project looks familiar later. Module 01 sets one up step by step, with a lockfile, a test runner and a type checker.
# uv (astral.sh/uv): package manager, venv, and Python versions in ONE tool.
# Your package.json instincts transfer directly (as of Aug 2026):
curl -LsSf https://astral.sh/uv/install.sh | sh # install once per machine
uv init demo && cd demo # pyproject.toml == package.json
uv add httpx "pydantic>=2.7,<3" # npm install --save (exact pins -> uv.lock)
uv add --dev mypy pytest # devDependencies
uv run python main.py # npx: runs inside the project venv, no "activate"
uv run mypy . # dev tools resolve from the same lockfile
uv sync # npm ci: reproduce the env bit-for-bit anywhere
- The cache is the whole story. The first import runs the file and stores the resulting module object under its name. Every later import is a dictionary lookup that returns that same object. So module-level code is an initialiser that runs once, and two modules that import each other get the half-built version, which is the one real hazard here.
- One file, two roles. Python sets
__name__to"__main__"in the file you asked it to run, and to the module's own name everywhere else. Guarding the self-test with that check is what lets the same file be both a program and a library. Without the guard, importingmetricswould run its self-test as a side effect of the import. - The packaging chain.
pyproject.tomlis the range you asked for anduv.lockis the exact set that satisfied it, down to hashes.uv syncbuilds.venv/from the lock file, so two machines get byte-identical dependencies.uv runthen uses that folder without any activation step, which is the part that removes the classic "it works on my machine" failure. Module 01 sets all four up properly.
Predict: metrics.py starts with a top-level
print("loading metrics"). Another file runs import metrics twice in a
row. How many times does it print — and what would python3 metrics.py print?
Reveal the answer
Once. The first import executes the file (printing the line); the second finds
metrics already in sys.modules and reuses it — module top-level code
is effectively a memoized initializer. Running python3 metrics.py directly prints
the line too, and runs anything under if __name__ == "__main__":,
because now the file is the program, not an import.
The stack, and why
Before the type-hint section, here is every tool this page leans on, and what you would pick instead.
The stack, and why
The one question that decides it: do you need this project to run the same way on someone else’s machine next year? (As of November 2026.)
| Layer | We use | Alternatives | Why this one | Switch when |
|---|---|---|---|---|
| Language and runtime | CPython 3.12, standard library only (every *_tour.py file) | Newer CPython 3.x, PyPy, TypeScript, Go | The default interpreter that every AI library targets first. Weakness: slow for hand-written loops over millions of items. | PyPy only for long pure-Python loops with no C libraries; Go or Java for a service where one request must cost well under 1 ms of CPU. |
| Project and environments | uv (previewed in §08, set up in Module 01) | pip with venv, Poetry, conda | One tool for the interpreter, the virtual environment and the lock file, and very fast. Weakness: newer than pip, so some old tutorials do not match it. | conda when you need non-Python system libraries such as CUDA builds; plain pip when a locked-down server only allows it. |
| Type checking | Type hints checked by mypy (typing_tour.py) | pyright, ty, no checker | Mature and the one most tutorials show. Weakness: slower than newer checkers on big code bases. | pyright when your team lives in VS Code; ty (still in beta as of late 2026) once your code base takes more than about 30 seconds to check. |
| Records | Dataclasses (classes_tour.py), with Pydantic at the edges | NamedTuple, TypedDict, attrs | Dataclasses are in the standard library and cost nothing to import. Weakness: they do not check types at run time. | Pydantic the moment the data comes from outside your program (an API body, an LLM reply, a file). |
| Number crunching | NumPy (list_vs_numpy.py, section 11) | Plain lists, the array module, Polars | One block of raw numbers in C, so 1,000,000 values add in milliseconds. Weakness: an extra install, and arrays have one fixed type. | Plain lists below about 1,000 numbers; a data-frame library such as Polars once you have named columns (see Python for data). |
| Tests | An assert self-test under __main__ (metrics.py) | pytest, unittest | Nothing to install, and it shows the idea. Weakness: it stops at the first failure and gives no report. | pytest when you have more than a handful of tests or need fixtures; it is what the later modules use. |
Start with the standard library and one tool (uv), and add a library only when a named problem, such as validation or speed, appears.
09 · Core PythonType Hints That Matter
Marcus is a TypeScript engineer, so this is the section where he asks where his compiler went. The honest answer is that there is no compiler. There is a separate program you choose to run, and it reads hints that the interpreter itself throws away. The habit being replaced is trusting the build to stop a bad call before it ships. What replaces it is hints on the borders plus a checker in the pipeline, which is also what will catch the mistakes an LLM makes in Module 15 when it writes code inside his repository.
Before the objection below, look at the split, because everything in this section follows from it. One signature, two readers, and only one of them cares.
- Two readers, one source. The annotations are ordinary parts of the source. The checker on the left is a program you install and run, like a linter. The interpreter on the right stores them on the function and never consults them. Nothing in Python enforces a hint at run time, and no hint makes your code slower.
- What you get for the effort. One bad call, one exact message, before anything runs: the argument name, the type you passed, the type expected, and a code you can look up. Run it in your editor and you get the same message as a red squiggle; run it in the pipeline and a wrong call cannot merge.
- What you do not get. The same wrong call, if you never run the checker, just runs. It may work by accident, or it may fail three functions later inside somebody else's code, which is the
TypeErrorinsum(). This is also why a wrong annotation is worse than none: it passes at run time and lies to every reader. Pydantic, in Module 01, is the piece that actually checks at run time, at the borders where the data is untrusted.
"Eight sections in and half these functions have no types on them. Where are my types? In Go the compiler would have thrown this whole page back at me."
— a Go engineer, and every Java engineer, right about now
They are optional, and that is a design choice you will have to make peace with. The split
is marker 1 of Fig. A1.2g, directly above: the same signature is read by two programs, and only
the one on the left cares. That left-hand program is mypy or pyright,
and marker 2 is the message it gives you for one wrong argument. Marker 3 is what the
interpreter does with the very same call, which is run it. A script with no hints runs; a
script with wrong hints also runs. The checker is a linter you choose to run, locally and in
CI.
What you get in exchange is a gradual dial. The tour scripts above hint every function signature and leave the local variables alone, because the checker infers those. Course code is written that way on purpose: hints on the borders, where a wrong type does damage, and nothing in the middle. In Module 15 those border hints are what let mypy catch mistakes in code an LLM wrote for you.
The honest downside: nothing stops a wrong annotation from shipping. A function hinted -> int that returns a string passes at run time and misleads every reader until the checker runs. Some libraries ship poor or missing type information, so Any leaks in and the checker goes quiet exactly where you wanted it loud. Pydantic, in Module 01, closes that gap at the boundaries that matter.
Python's type hints are TypeScript's deal with different fine print: annotations are
ignored at runtime (no compile step rejects a bad call) and enforced by an external
checker — mypy or pyright — run like a linter, locally and in CI. The
modern syntax is compact: built-in generics (list[str], dict[str, int] —
no List import since 3.9) and pipe unions (str | None — the honest
"maybe missing" type, your string | null).
Step-by-step: what typing_tour.py does, in plain English
- Import
TypedDict. It describes the shape of a dict for the type checker: which keys exist and what type each value has. At run time aTicketRowis an ordinary dict. - Define
slow_ids: it takes a list of rows and a cutoff with a default, and returns a list of strings. The body is the same filter-and-map comprehension from section 04. - Define
find: it returns either a row orNone, and the hintTicketRow | Nonesays so out loud. The body collects matches and returns the first, orNoneif there were none. - Build two rows and call both functions. The prints show a list with one id, then
Nonefor an id that does not exist. - The last line is a comment showing what
mypywould reject: passing the string"1000"where an int is expected. Python itself would run that call and fail later, inside the comparison.
# stdlib only -- run: python3 typing_tour.py check: uv run mypy typing_tour.py
from typing import TypedDict
class TicketRow(TypedDict): # the SHAPE of a dict, for the checker's eyes
id: str
ms: int
def slow_ids(rows: list[TicketRow], cutoff_ms: int = 1000) -> list[str]:
return [r["id"] for r in rows if r["ms"] > cutoff_ms]
def find(rows: list[TicketRow], id: str) -> TicketRow | None: # may be absent
matches = [r for r in rows if r["id"] == id]
return matches[0] if matches else None
rows: list[TicketRow] = [{"id": "T-1", "ms": 1400}, {"id": "T-2", "ms": 90}]
print(slow_ids(rows)) # ['T-1']
print(find(rows, "T-9")) # None
# mypy would reject: slow_ids(rows, cutoff_ms="1000") [arg-type]
| Option | Choose when | Avoid when | Runtime cost |
|---|---|---|---|
TypedDict | Data is already a dict (JSON in flight) and you only want checker-time shape safety | You need methods, defaults, or validation | Zero — it IS a dict |
@dataclass | Internal state you construct yourself; want __init__/__eq__/repr free | Data arrives from outside and might be malformed | Tiny — plain attributes |
| Pydantic model | Data crosses a boundary: API payloads, LLM structured outputs, config | Hot inner loops that never see untrusted data | Validation on construct — worth it at borders |
Why this section earns its place in an AI course: typed Python is the substrate of the whole
2026 LLM stack. Pydantic models are type hints turned into runtime validators; FastAPI
and FastMCP generate schemas from your annotations; and when you point an LLM coding agent at your
codebase in Module 15, type hints are precisely what lets it — and mypy — catch the
agent's mistakes before runtime. Untyped Python plus an eager code-generating LLM is how subtle
bugs ship; typed Python turns a whole class of them into red squiggles.
Given def avg(xs: list[float]) -> float: return sum(xs) / len(xs) —
which of these does mypy flag, and what happens at runtime for each?
(a) avg([1, 2, 3]) (b) avg(["1", "2"])
Reveal the answer
mypy flags only (b) — list[str] isn't list[float]. It accepts (a)
because int is compatible where float is expected. At runtime, (a)
returns 2.0; (b) crashes with TypeError inside sum() —
the hints did nothing to stop it, because hints are never enforced at runtime. That division of
labor — checker before runtime, nothing during — is the whole model.
There are no dumb questions
- Indentation as syntax — seriously? What happens when tabs and spaces mix?
- Python 3 refuses to run a file that mixes them ambiguously, so the horror stories are
mostly Python-2 folklore. In practice you'll never think about it: every editor inserts 4
spaces, and formatters (
ruff format, Module 01) normalize everything. You already indent your braces-language code exactly like this — Python just deleted the redundant characters. - Isn't Python too slow for AI work?
- Your Python is the orchestration layer; the heavy math runs in C, C++, and CUDA underneath numpy and PyTorch. LLM applications specifically spend their lives waiting on the network, where Python's speed is irrelevant and its async story (Module 01) is what matters. When you do hit CPU-bound Python, the fixes are vectorization or processes — covered exactly there.
- Why do I have to write
selfeverywhere? - Because methods are ordinary functions stored on a class, and Python makes the receiver an
explicit parameter instead of an implicit
this.t.close()is sugar forTicket.close(t). One rule ("first param is the instance") replaces a chapter ofthis-binding rules — ask a JS developer aboutbind()sometime. - Which Python version does the course assume?
- 3.12, pinned via uv in Module 01 (as of Aug 2026). Everything on this page needs only
3.10+ —
list[str]generics andX | Noneunions are the newest syntax used. Ifpython3 --versionsays 3.10 or later, every block here runs as-is. - Do I need to memorize the standard library?
- No. The ~20 constructs on this page cover about 95% of the Python you'll read in this course. The stdlib is a lookup problem — and you have an LLM for lookup problems. Fluency in the constructs is the part lookup can't give you.
10 · Watch it breakThe Five Classic Gotchas, Demonstrated
Nine sections of how Python works. This one is the bill. Five things compile, run, and quietly do the wrong thing, and four of the five come straight from the picture in section 03: a name is an arrow to a shared object. They are also the five questions a screening interview asks in its first fifteen minutes, which is the other reason Marcus needs them by name. The habit being replaced is the quiet assumption that something, somewhere, made a copy.
Every one of these compiles, runs, and silently does the wrong thing — Python's five classic traps for engineers arriving from other languages. Each traces back to one of two facts you've already met: names are references to shared objects, and some things are evaluated once, earlier than you think. Run the block, watch it lie to you, and you're inoculated — these five are also the top Python screening questions in interviews.
Here is the same three calls drawn on one timeline, with the contents of the default list written under each call. Check your four lines against it before reading on.
def runs, and every call that omits the argument appends to that same list.- The moment the list is made. It is made once, while the
defline executes, which is before any call happens. It is not made fresh per call. That single fact is the whole gotcha, and it is why the growing contents under calls 1 and 2 are the same object twice, not two objects. - Why
achanged after it was returned.anever changed. Call 1 returned a pointer to the list, and call 2 appended to that same list. Printingaafterwards shows two items because the object behind the arrow grew. This is Fig. A1.1b marker 2 with a function wrapped around it. - Why call 3 escaped. It passed its own list, so the default was never touched. That is also the shape of the fix: default to
None, and build a fresh list inside the body when nothing was passed. The dataclass version of the same fix isfield(default_factory=list), which is exactly whyCard.tagsis written that way in Fig. A1.2d.
Build it in chunks
We build gotchas.py in three chunks, two or three gotchas at a time. Each chunk runs on its own; the whole file comes at the end. The files are in code/a1-python-primer/ladder/.
-
Chunk 1 — the mutable default argument, and its fix
This is the gotcha that bites first and most often, and it needs no imports, so it is the smallest runnable program in the file.
Step-by-step: what chunk 1 does, in plain English
add_cardhas a defaultdeck=[]. That empty list is made once, whendefruns.- Calling it twice without a deck appends to the same list both times, so the second call shows both cards.
add_card_fixedusesNoneas a marker and builds a fresh list inside each call.
gotchas.py — chunk 1runs offline# GOTCHA 1 -- the mutable default argument (THE classic) def add_card(front, deck=[]): # [] is evaluated ONCE, at def time deck.append(front) return deck print(add_card("a")) # ['a'] print(add_card("b")) # ['a', 'b'] <- surprise: same list as the last call! def add_card_fixed(front, deck=None): # the idiom: None sentinel... deck = deck if deck is not None else [] # ...fresh list per call deck.append(front) return deck print(add_card_fixed("b")) # ['b']Default argument — evaluated once at
deftime, not on every call.Run
python3 chunk1_default.py. You should see these three lines:['a'],['a', 'b'],['b']. -
Chunk 2 — late-binding closures and shallow copies
Both gotchas are the same kind of surprise as chunk 1: Python keeps a pointer, not a snapshot. Closures point at a variable; a shallow copy points at the same inner lists.
Step-by-step: what chunk 2 does, in plain English
- Build three lambdas in a loop. Each looks up
ionly when called, by which time the loop has ended at 2, so all three return 2. - Give the lambda a default
i=iand each freezes the value it saw. - Make a 2 by 2 grid, copy it with
list(grid), change one inner cell through the copy and see the original change too. copy.deepcopycopies all the way down, so changing the deep copy leaves the original alone.
gotchas.py — chunk 2runs offlineimport copy # at the top of the file # GOTCHA 2 -- late-binding closures: `i` is looked up at CALL time fns = [lambda: i for i in range(3)] print([f() for f in fns]) # [2, 2, 2] -- not [0, 1, 2]! fns = [lambda i=i: i for i in range(3)] # default arg captures i's value NOW print([f() for f in fns]) # [0, 1, 2] # GOTCHA 3 -- copying copies the box, not the contents grid = [[0, 0], [0, 0]] shallow = list(grid) # new outer list, SAME inner lists shallow[0][0] = 9 print(grid[0]) # [9, 0] <- mutated through the "copy" deep = copy.deepcopy(grid) deep[1][1] = 7 print(grid[1]) # [0, 0] -- deep copy is independentcopy.deepcopy— copies a nested structure completely; a lambda default argument as a snapshot trick.Run
python3 chunk2_closure_copy.py. You should see the three lines from chunk 1, then the four new ones (the last four values below):['a'],['a', 'b'],['b'],[2, 2, 2],[0, 1, 2],[9, 0],[0, 0]. - Build three lambdas in a loop. Each looks up
-
Chunk 3 — mutating a list mid-loop, and floats (this is the whole program)
The last two gotchas are independent of the first three, so they come last. With them the file is complete.
Step-by-step: what chunk 3 does, in plain English
- Loop over
[2, 2, 3]and remove each even number. Removing shifts the next item into the slot the loop already passed, so the second 2 is skipped and the list ends as[2, 3]. - A list comprehension builds a new list instead and gets the right answer,
[3]. - Add 0.1 and 0.2: the sum is 0.30000000000000004, and
==against 0.3 is False. math.isclosecompares with a small tolerance and returns True.
gotchas.py — chunk 3runs offlineimport math # at the top of the file # GOTCHA 4 -- never mutate a list you're iterating nums = [2, 2, 3] for n in nums: if n % 2 == 0: nums.remove(n) # shifts elements under the iterator print(nums) # [2, 3] <- it MISSED the second 2 print([n for n in [2, 2, 3] if n % 2]) # [3] -- build a new list instead # GOTCHA 5 -- floats are binary fractions (every language; Python shows it) print(0.1 + 0.2) # 0.30000000000000004 print(0.1 + 0.2 == 0.3) # False print(math.isclose(0.1 + 0.2, 0.3)) # True -- compare with tolerance, alwaysmath.isclose— compare floats with tolerance; list comprehension with a condition as the safe way to filter.Run
python3 chunk3_loop_float.py. The last five values are the new ones; the whole output is:['a'],['a', 'b'],['b'],[2, 2, 2],[0, 1, 2],[9, 0],[0, 0],[2, 3],[3],0.30000000000000004,False,True. - Loop over
The whole program
Chunk 1 is gotcha 1, chunk 2 is gotchas 2 and 3, chunk 3 is gotchas 4 and 5. Each chunk starts with a # ── chunk n ── comment. The two imports sit at the top of the file, where Python expects them: copy is used from chunk 2 and math from chunk 3.
Step-by-step: what gotchas.py does, in plain English
- Import
copyfor deep copies andmathfor tolerant float comparison. - Gotcha 1. Define
add_cardwithdeck=[]. That list is created once, whendefruns. Two calls that omitdeckboth append to it, so the second call prints['a', 'b']. - The fix: default to
None, then inside the body build a fresh list when nothing was passed. Each call now starts empty. - Gotcha 2. Build three lambdas in a comprehension, each returning
i. They do not capture the value ofi; they look it up when called, and by then the loop has finished at 2. All three return 2. - The fix:
lambda i=i: i. A default argument is evaluated at definition time, so each lambda freezes theiit saw. - Gotcha 3.
list(grid)makes a new outer list whose slots point at the same inner lists. Changing an inner value through the copy changes the original.copy.deepcopycopies all the way down, so the deep copy is independent. - Gotcha 4. Remove items from a list while looping over it. Removing the first 2 shifts the second 2 into the slot the loop has already passed, so it is skipped. Build a new list with a comprehension instead.
- Gotcha 5. Add 0.1 and 0.2: binary floats cannot hold either exactly, so the sum is not 0.3 and
==says False. Compare withmath.isclose, which allows a tiny tolerance.
# stdlib only -- run with: python3 gotchas.py
# ── chunk 1: the mutable default ──
import copy
import math
# GOTCHA 1 -- the mutable default argument (THE classic)
def add_card(front, deck=[]): # [] is evaluated ONCE, at def time
deck.append(front)
return deck
print(add_card("a")) # ['a']
print(add_card("b")) # ['a', 'b'] <- surprise: same list as the last call!
def add_card_fixed(front, deck=None): # the idiom: None sentinel...
deck = deck if deck is not None else [] # ...fresh list per call
deck.append(front)
return deck
print(add_card_fixed("b")) # ['b']
# ── chunk 2: closures and copies ──
# GOTCHA 2 -- late-binding closures: `i` is looked up at CALL time
fns = [lambda: i for i in range(3)]
print([f() for f in fns]) # [2, 2, 2] -- not [0, 1, 2]!
fns = [lambda i=i: i for i in range(3)] # default arg captures i's value NOW
print([f() for f in fns]) # [0, 1, 2]
# GOTCHA 3 -- copying copies the box, not the contents
grid = [[0, 0], [0, 0]]
shallow = list(grid) # new outer list, SAME inner lists
shallow[0][0] = 9
print(grid[0]) # [9, 0] <- mutated through the "copy"
deep = copy.deepcopy(grid)
deep[1][1] = 7
print(grid[1]) # [0, 0] -- deep copy is independent
# ── chunk 3: mutating a loop, and floats ──
# GOTCHA 4 -- never mutate a list you're iterating
nums = [2, 2, 3]
for n in nums:
if n % 2 == 0:
nums.remove(n) # shifts elements under the iterator
print(nums) # [2, 3] <- it MISSED the second 2
print([n for n in [2, 2, 3] if n % 2]) # [3] -- build a new list instead
# GOTCHA 5 -- floats are binary fractions (every language; Python shows it)
print(0.1 + 0.2) # 0.30000000000000004
print(0.1 + 0.2 == 0.3) # False
print(math.isclose(0.1 + 0.2, 0.3)) # True -- compare with tolerance, always
Gotcha 1 deserves the diagram, because the fix (None sentinel, and
field(default_factory=list) back in the dataclass section) only sticks once you see
the mechanism: default values live on the function object, created once when
def executes — so every call that omits the argument shares one list.
- The function object holds the defaults. A function in Python is an object, and its default values are stored on it in an attribute called
__defaults__. The dot in that tuple is a pointer, not a value. Every default you write lives there from the momentdefruns until the program ends. - The one list. Because the pointer never changes, there is exactly one list for the life of the function, and it is the accented box. Appending to it in one call is visible in the next, which is why the second call prints
['a', 'b']. An immutable default such as0or"p95"is harmless here for exactly this reason: nothing can change it. - Both calls bind to it. Each call that omits the argument binds its local name
deckto that same object, on the left and on the right of the picture. A caller who passes a list of their own binds to theirs instead and never touches this one, which is the third station in Fig. A1.2h.
Before the two of them argue, look at what each one actually costs and refuses. Every claim in the chat below points at a numbered row in this picture, and all five numbers came off this page's own code.
- Memory. The measured sizes from the pencil exercise in Fig. A1.2b: 36,448,728 bytes against 200. This is the row the generator wins outright, and the gap grows with the input.
- The second pass. A list gives the same answer a thousand times. A generator gives it once and then answers 0 for ever, with no error to tell you. This is the row that costs people an afternoon.
- Random access.
len(),xs[500]and slicing are list-only. On a generator all three raiseTypeError, and the cure is alwayslist(gen), which pays the memory bill in row 1 on purpose. - Values that do not exist yet. A model producing tokens, a 10 GB log being read, a socket delivering rows. A list has to wait for all of them and then hold all of them. A generator hands each one on as it appears.
- Saving. Anything you want to write to disk, put in JSON or send over a wire has to be data. A generator is not data; it is a recipe with a bookmark in it. That is why every result that leaves a program ends up in a list, a dict or a file.
- The rule. Two lines, and they decide it every time. Walk once, large, or still arriving: generator. Look twice, index, sort, save: list. Nothing else in the argument below changes this answer.
Tonight's talk: The List and The Generator argue over the question, "Who's more important?"
Let's start with what the reader can see. Marker 3. Print me and you get my contents. Ask my length and you get a number. Ask for item 500 and you get item 500. All three of those are a TypeError on you. Print you and you get <generator object <genexpr> at 0x7f...>. That is not a data structure, that is an IOU.
a list can be printed, measured and indexed straight away. A generator supports none of that, because it has not computed anything yet.
An IOU that never asks for 36 megabytes up front. Marker 1: the same million values are 36,448,728 bytes through you and 200 bytes through me, measured, not guessed. And marker 4 is the row you cannot argue with. When a model streams its answer one token at a time, the tokens do not exist yet. You cannot hold what has not arrived. I can.
the memory gap in row 1 is measured on this page, and row 4 is the case where a list is not slower but impossible: the values have not been produced yet.
And when the reader wants to look twice? Marker 2. The first sum answered 999,999,000,000 and the second answered 0. No error, no warning, just a wrong number sitting in a report. I can be walked a thousand times and give the same answer every time. You are single-use, and you fail silently, which is the worst way to fail.
row 2: a generator can be walked once. The second walk finds nothing and quietly returns the sum of nothing, which is zero.
Silently? Read gotchas.py again. The reader removed items from you while looping over you and you skipped an element without a sound. Two lines earlier, list(grid) copied your outer box and shared your insides, so a write through the copy changed the original. I have no insides to share. Nobody can mutate me mid-loop, because I am the loop.
lists have silent failures of their own. Removing items while iterating skips some, and a shallow copy still shares the inner lists.
Those are misuse, not design. Marker 3 again: slicing, len(), item 500. Every one of those is a TypeError on you, and the fix is always the same, list(gen) — which pays marker 1's bill on purpose. The moment a program needs to do anything but walk forward once, it turns you into me.
row 3 is the reason generators keep being converted back into lists, and that conversion is exactly the memory cost of row 1.
Because turning me into you is cheap and the reverse is not. Marker 4, in practice: a pipeline of three generators reads a 10 GB log in constant memory and starts printing results before the first megabyte is done. Rebuild that with lists and you wait for the whole file to load, then hold three copies of it. Being convertible is my strength, not my weakness.
generators chain without materialising anything in between, so a three-stage pipeline still holds one row at a time.
Your body does not even run when you are called. The reader saw it in the countdown prediction: countdown(3) printed nothing, and "starting" only appeared on the first next(). An exception in your body is raised where you are consumed, which can be three functions away from where you were written. Debugging that is a treasure hunt.
calling a generator function runs none of its body, so errors inside it surface later, at the place that consumes it.
Laziness is the feature. The sum(i * i for i in range(n)) inside timed.py never built a list of a million squares, and nobody had to think about it. That expression is me, in round brackets. The reader has been using me all page without noticing, which is the highest compliment a data structure can get.
a generator expression inside a call needs no extra brackets, so most readers never notice they are using one.
And every one of those results was stored in me afterwards. Marker 5. JSON serialises me. The cards in deck.json live in me. You cannot be written to disk, pickled, or sent over a wire, because you are not data. You are a promise to compute data.
row 5: anything that leaves the program has to be data, so results end up in a list, a dict or a file.
A promise that scales. Marker 6, the band across the bottom, is the rule the reader should take home, and we both agreed to it. Walk once, or the input is large or still arriving: use me. Look twice, index, sort, or save: use you. We'll revisit who's more important when the reader hits a file that does not fit in memory.
the bottom band is the decision rule, and it is the one line worth memorising from this whole argument.
Or a bug that does not fit in a traceback. Your move.
neither wins. The picture above is the answer: pick the row that matches what your code actually needs to do.
11 · Under the hoodHow CPython Actually Runs Your Code
Marcus can now read the course's Python. The last thing he needs is why it behaves the way it does when it gets slow, because that is the question his team will ask him in review. Three facts carry most of it: the source is compiled to bytecode, one lock lets one thread run that bytecode, and an object is freed the moment nothing points at it. The habit being replaced is reaching for a thread pool when a program is slow. In Python the right question is first: is it waiting, or is it computing?
Optional depth — but it makes three course-relevant facts click. When you run
python3 app.py, CPython compiles your source to bytecode (cached in
__pycache__/*.pyc, which is why second runs start faster), then a bytecode
interpreter — the Python Virtual Machine — executes it one instruction at a time. So Python is
compiled and interpreted, like Java without the JIT tier.
- Your source. The file you wrote, read once from disk. Nothing in it is executed at this stage; it is parsed into a tree first, which is where a syntax error is reported, before a single line of your program has run.
- The bytecode. A list of small instructions for a stack machine, the same idea as JVM bytecode. It is cached in
__pycache__next to the file, which is why the second run of an imported module starts faster. The disassembly at the end of this section prints these instructions for a one-line function. - The eval loop. A loop in C that fetches one instruction, does it, and fetches the next. This is where your program actually runs, and it is also where Python's reputation for slowness comes from: every addition is a trip around this loop, with type checks on the way.
- The lock. The Global Interpreter Lock is a mutex around that loop. One thread holds it at a time, so two threads never execute Python instructions at the same instant. It is released while a thread waits on the network or the disk, which is the difference that decides whether threads help you at all.
Now the same pipeline a second time, with this page's actual files in the boxes. If a stage in Fig. A1.4 feels abstract, find its row here: every stage is something you have already run on this page, or will run in Module 01.
| Stage | Running one file by hand (sections 03 to 07) | In a uv project (section 08, Module 01) | What flows out |
|---|---|---|---|
| Pick the interpreter | Whatever python3 is first on your PATH | uv pins the version in the project and uv run selects it | One known Python version |
| Resolve packages | Nothing: every tour script is stdlib only | uv add httpx "pydantic>=2.7,<3" writes pyproject.toml and uv.lock | A venv that matches the lockfile on every machine |
| Parse and compile | python3 collections_tour.py compiles the file to bytecode in memory | The same; imported modules cache their bytecode in __pycache__/ | Bytecode, the instructions dis shows below |
| Import | import metrics runs metrics.py once and stores it in sys.modules | The same; the __main__ guard keeps self-tests out of imports | Module objects, one per file |
| Execute | The eval loop runs one instruction at a time under the GIL | The same, plus asyncio for network waits and processes for CPU work | Printed output, files, API calls |
| Check types | None: typing_tour.py runs with its hints ignored | uv run mypy . before commit and in CI | Errors caught before the program runs |
| Free memory | Reference counting frees an object when its last name goes away | The same; with blocks make file and connection release deterministic | Memory returned, files closed |
Memory: CPython frees objects primarily by reference counting — every object
carries a count of names/containers pointing at it, and hits zero → freed immediately (that
deterministic cleanup is why with blocks feel so predictable). A backup cycle
collector (gc) sweeps up reference cycles that counting alone can't reclaim.
That's the whole story at course depth.
The GIL, in three sentences. The Global Interpreter Lock lets only one thread execute Python bytecode at a time, so threads give you concurrency (useful while waiting on I/O, since the GIL is released during blocking calls) but not CPU parallelism.
That's why Module 01 teaches the rule: async for I/O-bound work (LLM calls are 99% waiting on the network) and processes for CPU-bound work (each process gets its own GIL).
Python 3.13+ ships an experimental free-threaded build, but as of Aug 2026 the async-vs-processes rule is still how production AI code is written.
Both halves of that rule are measurable, so here they are measured. The top of the picture is waiting work, which is what an LLM call is. The bottom is computing work, which is where the lock from marker 4 of Fig. A1.4 decides the outcome.
- Waiting work. Each bar is a call that spends its two seconds waiting for a reply.
awaitlets the one thread start the next call instead of sitting still, so all three bars overlap and the whole thing takes as long as the slowest one. The same three calls withoutawaitlie end to end and take 6.01 s. No extra threads, no locks, and this is the shape of every batch of LLM requests in this course. - Computing work. The shaded blocks are the moments a thread is actually running instructions, and they never overlap, because the lock is handed over at every dashed line. Two threads therefore finish no sooner than one, and the hand-offs cost real time, which is why the threaded run came out slower than the serial one. Two processes have two interpreters and two locks, so they genuinely halve the work.
- The rule you take away. Ask what the program is doing while it is slow. If it is waiting, use
asyncand one thread. If it is computing, use processes, or push the loop into a library that does the arithmetic in C, which is what numpy and PyTorch are. Threads are for waiting, and only for waiting.
"One bytecode at a time, one thread at a time, and a reference count on every object. Why is Python so slow, and why does the entire AI industry use it anyway?"
— a Go engineer who just read Fig. A1.4
Both halves of the question are fair. A loop written in plain Python runs ten to a hundred times slower than the same loop in Go or Java. Every add is a trip through the eval loop, with type checks on the way. That cost is real, and a faster machine only hides it.
The industry uses Python because the slow part is almost never Python. The matrix multiply inside numpy or PyTorch runs in C, C++ and CUDA; the Python line that called it was one instruction. An LLM application spends its life waiting for the network, and a language that waits well, with asyncio, beats one that computes fast. Python is the glue, and glue is where the libraries and the hiring are.
The honest downside: leave the libraries and write a hand-rolled loop over a million records, and you pay the full price. Marker 2 of Fig. A1.4b is that price with a stopwatch on it: the same arithmetic took 0.62 s in one thread and 0.92 to 1.76 s in two, because the lock is handed back and forth instead of the work being shared. The fixes are real but they are extra work. Push the loop into numpy, move it to a process pool, or write that one hot function in Rust. Module 01 shows the first two.
Questions you might be asking now
The bubble above ends on "push the loop into numpy" as if that phrase explained itself. The questions below slow down for it. Every answer starts from the same three latencies, then scales up to the million values of Fig. A1.2b and timed.py.
| Ticket | priority | ms | ms ÷ 1000, in seconds |
|---|---|---|---|
| T-101 | high | 4,200 | 4.2 |
| T-102 | low | 950 | 0.95 |
| T-103 | high | 380 | 0.38 |
Is a Python list the same thing as a numpy array?
No. A list is a row of arrows to separate Python objects, and every one of those objects carries its own type and bookkeeping. A numpy array is one block of raw numbers that all share a single type. For the million values of Fig. A1.2b that is 36,448,728 bytes as a list against 8,000,112 bytes as an array, 4.56 times smaller.
Start from what you already know. Fig. A1.2b split the list's memory into two pieces: the slots, and the million integer objects the slots point at. A numpy array keeps no per-number objects at all. It stores the numbers themselves, side by side, as 8-byte machine integers.
In Java terms, a numpy array of integers is a long[]. A Python list is closer to an ArrayList<Long>: a row of references to boxed numbers. numpy is the third-party package for arrays of numbers that the AI stack stands on: pandas and scikit-learn are built on it, and PyTorch's tensors use the same design.
Here are the bytes for the three latencies, counted by hand and then checked with sys.getsizeof by list_vs_numpy.py.
- The list object. A 56-byte header, plus room for 4 slots at 8 bytes each: 56 + 4 × 8 = 88 bytes. The literal
[4200, 950, 380]keeps one spare slot for the nextappend. - The three int objects. Each one is 28 bytes: an 8-byte reference count, an 8-byte pointer to its type, an 8-byte size field and 4 bytes of digits. 3 × 28 = 84 bytes.
- The list's total. 88 + 84 = 172 bytes, spread over 4 separate objects.
- The array. A 112-byte header, holding the array's bookkeeping: its shape, its type and where its data starts. Then the three numbers as 8-byte cells: 112 + 3 × 8 = 136 bytes, all in 1 object.
- Scale it up. Each header is paid once; the per-number cost is what grows. That is about 8 + 28 = 36 bytes per value for the list, against 8 for the array. For the million values of Fig. A1.2b: 8,448,728 + 28,000,000 = 36,448,728 bytes, against 8,000,112.
- Four objects for three numbers. The list itself is a header and a row of 8-byte slots, with one spare kept for the next append. Each slot holds an arrow, and each arrow lands on a separate 28-byte int object. That is Fig. A1.1b again: a list holds arrows, not numbers.
- One object, raw numbers. The array's header records the shape, the type and where the data starts. The data is three 8-byte cells holding 4200, 950 and 380 directly. There is no object per number, so there is no type to check per number either, which is what the next question is about.
- Why the gap grows. At three values the header dominates: 172 bytes against 136. At a million values the headers are noise, and the per-value cost decides it: about 36 bytes against 8. The list bar is the same 36,448,728 bytes drawn in Fig. A1.2b.
The difference is not only memory. The same symbols mean different things on the two types, and the last row of this table is the one that bites people:
| You write | On the list ms | On the array arr |
|---|---|---|
+ itself | ms + ms joins: [4200, 950, 380, 4200, 950, 380] | arr + arr adds each pair: [8400 1900 760] |
* 2 | Repeats the list: the same six items | Doubles each number: [8400 1900 760] |
/ 1000 | TypeError: unsupported operand type(s) | [4.2 0.95 0.38] |
| A mix of types | Fine: each slot points at any object | np.array([4200, "slow"]) turns both into strings: ['4200', 'slow'] |
| Grow by one | ms.append(5100) changes the list itself | np.append(arr, 5100) returns a new array; arr still has 3 |
| Slice, then write | ms[0:2] is a new list; writing to it leaves ms alone | arr[0:2] is a view; writing 0 into it changed arr to [0 950 380] |
That last row matters for this page in particular. Fig. A1.1c promised that a slice always hands back a new list, and for lists it does. An array slice is a view: a second arrow into the same block of numbers, so np.shares_memory printed True. When you mean a copy, write arr[0:2].copy().
The array is not simply the better list. It gives up what made the list useful: any mix of types, cheap appends, and a None in the middle. np.array([4200, None]) quietly becomes dtype object, which is a row of arrows again, with none of the savings.
Size matters too. For three values the gain is 172 bytes against 136. The array pays off when there are many numbers of one type: a column of latencies, an embedding, an image.
A list stores arrows to objects; an array stores the numbers themselves, in one block, with one type. Same brackets, different + and *, and an array slice is a view, not a copy.
What does "vectorised" actually mean? Show me a loop against one numpy line, measured.
Vectorised means you write one operation for the whole array, and the loop over the elements runs inside numpy's compiled code instead of Python's eval loop. Take the sum of squares of 0 to 999,999. timed.py's generator shape took 67.3 ms of CPU time here, and (a * a).sum() took 3.19 ms: 21 times faster, with the same answer.
The word borrows the maths sense of a vector: a whole row of numbers treated as one thing. In code it means you stop writing the loop yourself. You say "divide every latency by 1,000" once, and numpy does the dividing.
The time goes where marker 3 of Fig. A1.4 said it would: the eval loop. vectorised_timing.py asks the dis module what the list comprehension [m / 1000 for m in ms] compiles to. These seven bytecode instructions repeat for every element:
- FOR_ITER asks the list for its next item.
- STORE_FAST puts that item in the name
m. - LOAD_FAST pushes
mback onto the stack. - LOAD_CONST pushes the constant 1000.
- BINARY_OP divides. First it looks at the types of both operands to find the right division. Then it builds a new float object for the result.
- LIST_APPEND puts that float into the result list.
- JUMP_BACKWARD goes back to step A for the next item.
For the three tickets that is 3 × 7 = 21 trips through the eval loop. For a million values it is 7,000,000. The array line arr / 1000 compiles to one BINARY_OP for the whole array. numpy checks the type once, then runs a loop written in C over the raw 8-byte cells from Fig. A1.4e.
Now the same idea on a real workload: the sum of squares from timed.py, whose own comment printed 61.0 ms on another machine. "Per value" is the total divided by the count. For the first row: 67.3 ms ÷ 1,000,000 = 0.0000673 ms, which is 67 ns (nanoseconds, billionths of a second).
| Line | CPU time | Per value | Where the loop runs |
|---|---|---|---|
sum(i * i for i in range(n)), timed.py's shape | 67.3 ms | 67 ns | Python's eval loop |
for i in range(n): t += i * i | 62.8 ms | 63 ns | Python's eval loop |
sum([i * i for i in range(n)]) | 89.0 ms | 89 ns | Python's eval loop, plus a million-item list |
(a * a).sum(), with a = np.arange(n) | 3.19 ms | 3.2 ns | numpy's C loop, twice |
np.dot(a, a) | 0.81 ms | 0.8 ns | One C loop, no temporary array |
- Seven instructions per value. The row of boxes is what
disprinted for the loop inside[m / 1000 for m in ms]. The return arrow sends the eval loop back to FOR_ITER for every element. Each BINARY_OP inspects both operands' types before it can divide, and every result is a new float object. That is 21 trips for three tickets. - One instruction for all of them.
arr / 1000is a single BINARY_OP as far as Python can see. It hands the whole array to numpy, which checks the type once and runs a compiled loop over the raw cells drawn in Fig. A1.4e. The work per value is one division and nothing else. - The measured gap. The three red bars run through the eval loop and land between 63 and 89 ns per value. The green bars run in C: 3.2 ns, and 0.8 ns when
np.dotmultiplies and adds in one pass. On your machine every bar will be a different length, but the gap between red and green will still be there.
Why is (a * a).sum() not the fastest? It is two vectorised steps. a * a builds a whole new 8 MB array of squares, and then .sum() walks it. np.dot(a, a) multiplies and adds in one pass, with no temporary array, which is why it was about four times faster again.
Two honest limits. First, vectorised does not mean parallel: every line in the table ran on one core. The speed comes from skipping the per-value bytecode, type checks and new objects, not from extra processors. Second, it only works when the whole job can be said as array operations. The next question is about the cases where it cannot.
Vectorised means the loop moves out of Python's eval loop into numpy's compiled code: you write one operation, numpy checks the type once and runs through raw numbers. Same answer, here 21 to 83 times faster.
So should every loop become numpy? Where does it not help?
No. numpy wins when one operation covers many numbers of one type. It loses on short lists, on Python loops that walk an array one element at a time, and on anything that grows item by item. Its fixed-size integers can also overflow without a word: summing the squares of 10 million values gave 1,291,890,006,563,070,912, a wrong answer, with no warning.
Every numpy call has a fixed cost before it touches a single number: read the arguments, check the types, allocate the result. On a big array that cost disappears into the work. On three latencies it is the work. Here is the ms-to-seconds job at six sizes, from the three tickets up to a million values.
| Latencies | List comprehension | numpy, array already built | numpy, converting the list first |
|---|---|---|---|
| 3 | 0.1 µs | 1.4 µs | 1.8 µs |
| 30 | 0.8 µs | 1.4 µs | 2.7 µs |
| 100 | 2.7 µs | 1.4 µs | 4.7 µs |
| 1,000 | 26.2 µs | 2.3 µs | 31.9 µs |
| 100,000 | 2,610.6 µs | 65.6 µs | 3,017.6 µs |
| 1,000,000 | 44,150.0 µs | 2,389.5 µs | 31,965.4 µs |
Read the table in two ways. If the array already exists, numpy overtakes the list somewhere between 30 and 100 values. For the three tickets, the list comprehension took 0.1 µs against numpy's 1.4 µs.
If the numbers arrive as a Python list and you convert them for one operation, the conversion eats the gain. np.array(ms) has to visit every Python int object, which is the slow part all over again. The list comprehension stayed faster all the way to 100,000 values, and numpy won only at a million.
- Array ready. The green line is flat on the left: about 1.4 µs whether it divides 1 latency or 100. That flat stretch is numpy's fixed cost per call. The list comprehension starts near 0.1 µs and grows with every element, so it crosses the green line between 30 and 100 values.
- List arrives. The dashed line is the green one plus
np.array(ms). Converting visits every Python int, so the dashed line grows at the same rate as the list comprehension and runs just above it. It dips below only at a million values: 32.0 ms against 44.2 ms. - Looping over an array. Each element taken out of an array is wrapped in a new
numpy.int64object, and arithmetic on those is slower than on plain ints. The samesum(x * x for x in …)took 120.8 ms over the array and 45.1 ms over a list. - Growing one at a time. An array's block of cells cannot grow in place, so every
np.appendbuilds a new array and copies everything into it. The list'sappenduses the spare slots a list keeps for exactly this. - Overflow. The true sum needs 69 bits; an int64 has 64, and keeps only the remainder. A Python int grows as needed, so the plain Python loop got the exact answer, only more slowly.
The overflow, by hand
A Python int grows as large as it needs to. A numpy int64 holds at most 9,223,372,036,854,775,807, and past that it wraps around, exactly like a Java long. Here is the check, with every step:
- The formula. 0² + 1² + … + (n − 1)² = (n − 1) × n × (2n − 1) ÷ 6.
- Plug in n = 10,000,000. 9,999,999 × 10,000,000 × 19,999,999 ÷ 6 = 333,333,283,333,335,000,000. Python's plain loop printed exactly this.
- Compare with the int64 limit. About 3.3 × 10²⁰ against about 9.2 × 10¹⁸: the true sum is about 36 times too big to fit.
- Wrap around. An int64 keeps only the remainder after removing whole multiples of 2⁶⁴, which is 18,446,744,073,709,551,616. The true sum holds 18 of them: 333,333,283,333,335,000,000 − 18 × 18,446,744,073,709,551,616 = 1,291,890,006,563,070,912.
- Compare with numpy. numpy printed 1,291,890,006,563,070,912: the remainder, digit for digit, with no warning.
The fixes are choices you make on purpose. Use float64 when an approximate answer is fine; it printed 3.333333e+20. Keep the sum in Python ints when it must be exact. And know your largest value before you pick an integer type.
Reach for numpy when one operation covers many numbers of one type and the array already exists. For a handful of values, element-by-element loops, one-at-a-time growth or integers that may pass 9.2 × 10¹⁸, stay with plain Python or choose the dtype on purpose.
See the actual bytecode — optional depth
The dis module disassembles any function. For
def f(x): return x * 2 + 1, CPython 3.12 emits a load, two constant loads, and two
binary ops — a stack machine, like the JVM:
Step-by-step: what bytecode_peek.py does, in plain English
- Import
dis, the standard library's disassembler. - Define a one-line function so there is something small to inspect.
- Call
dis.dis(f). It prints every bytecode instruction the compiler produced: loadx, load the constant 2, multiply, load the constant 1, add, return. The comment lines show the 3.12 output; other versions print slightly different names and offsets.
# stdlib only -- run with: python3 bytecode_peek.py (3.12 output; yours may differ)
import dis
def f(x):
return x * 2 + 1
dis.dis(f)
# 0 RESUME 0
# 2 LOAD_FAST 0 (x)
# 4 LOAD_CONST 1 (2)
# 6 BINARY_OP 5 (*)
# 10 LOAD_CONST 2 (1)
# 12 BINARY_OP 0 (+)
# 16 RETURN_VALUE
Each of those instructions is one trip through the eval loop — and the GIL is exactly a mutex around that loop. "One bytecode at a time" is literal.
12 · The road aheadThe Python You'll Meet in This Course
That is the language. This section is the receipt. Marcus lost three weeks because five spellings arrived in the same screenful; the point of what follows is that from here they arrive one at a time, each inside a module that needs it for a job. The habit being replaced is learning a language front to back and hoping the useful parts turn up. Every construct below was chosen because a later module cannot be read without it.
Everything above was chosen backwards from the course itself. Here's the map from construct to the first place it carries real weight — when you hit one of these modules and a shape looks familiar, that's this appendix paying out:
| Construct | Doing what | First appears |
|---|---|---|
| Comprehensions | Every data-shaping line | Everywhere, from Module 01 |
| Pydantic models | Data contracts; LLM structured outputs | M01 · M06 |
| async / await | Concurrent LLM calls | M01 · M06 |
| Decorators | pytest fixtures; FastMCP tools; FastAPI routes | M07 · M10 · M12 |
| Dataclasses | Agent state | M09 |
| Context managers | Streaming LLM responses safely | M06 |
| Type hints | Letting mypy check LLM-generated code | M15 (and every lab) |
- The line is the course. Left to right in reading order, with one dot per module that needs something from this page. Everything above a dot is what that module assumes you can already read.
- The Module 01 cluster. Three of the seven land immediately, in the module Marcus closed the tab on. That is not bad course design; it is what a working stack needs on day one. It is also why this appendix exists and why it sits before Module 00.
- The decorator appears three times. A test fixture, a tool definition and a web route are the same shape you built in Fig. A1.2c: function in, wrapped function out. Learn it once here and three later modules stop looking like framework magic.
- Type hints pay last and pay most. They cost you nothing at run time all the way through the course, and then become the thing that catches an LLM's mistakes in your repository. That is the one construct whose value is not visible when you learn it.
The honest fluency math: an engineer who reads Python natively reviews AI code — teammates' and LLM-generated alike — three to five times faster than one mentally transliterating from another language, because fluent readers chunk idioms instead of parsing tokens. And Python isn't one option among many here: it's the lingua franca of every tool in this course and appears in 91–96% of AI job postings (see the market page). The elevator version: "Six focused hours buys permanent fluency in the language every AI tool speaks — it's the cheapest multiplier on every hour that follows."
13 · The labBuild the Tool You'll Study With
Six hours should end with something running. The lab builds a flashcard trainer whose deck is this page's own five gotchas, so the thing Marcus builds is the thing that keeps the page in his head. Every construct in the specification is there because the job needs it: a dataclass for the card, a comprehension for the due list, a generator for the drill, a decorator for the timing, and forgiveness-not-permission for the corrupt file. The habit being replaced is the last one, learning a language by reading about it.
Worked examples first, spec second — you've seen every ingredient this lab needs, most of them in this page's own code blocks. Note the meta-trick: you're building a spaced-repetition trainer whose deck is this appendix's own gotchas — the tool you build is the tool you'll use to retain the page. Here's the seed script (your 80%); the scheduler and CLI are your 20%:
Step-by-step: what seed_deck.py does, in plain English
- Import
jsonandPath. - Define
CARDS: five dicts, each with a front (the question) and a back (the answer). The five questions are this page's five gotchas. - Build the deck with a comprehension over the cards.
{**c, "streak": 0, "due": 0}copies each card's keys into a new dict and adds two scheduling fields. The double star here means "spread this dict's items in", like...objin JavaScript. - Wrap the list in an outer dict with a version number, so the file format can change later without breaking old decks.
- Write it to
deck.jsonin one call, indented so you can read the file, and print a confirmation with an f-string.
# stdlib only -- run once: python3 seed_deck.py
import json
from pathlib import Path
CARDS = [
{"front": "def f(x, acc=[]) -- what's wrong?",
"back": "The [] is created once at def time; every call shares it. Use acc=None."},
{"front": "[lambda: i for i in range(3)] -- each call returns?",
"back": "2. Closures look i up at call time (late binding). Capture with i=i."},
{"front": "list(grid) copies what, exactly?",
"back": "The outer list only -- inner lists are shared. That's a shallow copy."},
{"front": "0.1 + 0.2 == 0.3?",
"back": "False -- binary floats. Compare with math.isclose."},
{"front": "a is b vs a == b?",
"back": "is = same object (identity); == = same value. Use is only for None."},
]
deck = {"version": 1, "cards": [{**c, "streak": 0, "due": 0} for c in CARDS]}
Path("deck.json").write_text(json.dumps(deck, indent=2))
print(f"seeded deck.json with {len(CARDS)} cards") # seeded deck.json with 5 cards
- Loading, forgiveness style. The risky lines go in the
try: reading the file and parsing it. A missing file is a normal state and gets a helpful message; corrupt text becomes aValueErrorthat names the file. This is Fig. A1.2e with your own file name in it. - The card is a dataclass. Front, back, streak, due, all typed. You get the constructor, the printer and field-by-field equality for free, and
mypycan check every function that touches a card. - One comprehension picks the due cards. Filter on the due date, keep the card. One line, no accumulator, and the intent is readable in review: these are the cards due today.
- The generator hands them out. The drill walks the due cards once, in order, so a generator is the honest shape, and marker 6 of Fig. A1.3b says so. Note what you give up: no
len(), so if you want to print "card 3 of 7" you need the list as well. - The decorator times the drill. Exactly the ten lines you read in timed.py, applied to your own function. It is also where the spaced-repetition arithmetic lands: a correct answer pushes the next showing out to two to the power of the streak, in days.
Mission: build flashcards.py so that
python3 flashcards.py drill shows each due card's front, waits for
Enter, reveals the back, and asks "got it? [y/n]" — y bumps the card's streak and
pushes its due date out (e.g. due = now + 2**streak days), n resets
the streak to 0. State persists to deck.json between runs. Every construct below
must appear because the job needs it, not as decoration.
Cardis a@dataclasswith full type hints; deck round-trips todeck.jsonviapathlib+json- Due-card selection is a single comprehension over the deck
- At least one generator used meaningfully (e.g. lazily yielding due cards to the drill loop)
- At least one decorator used meaningfully (e.g.
@timedon the drill, or a@requires_deckguard that seeds a missing file) - Malformed deck handled EAFP-style: missing file → helpful "run seed_deck.py" message; corrupt JSON →
ValueErrornaming the file, no raw traceback - Measurement criterion:
uv run mypy flashcards.pyexits clean (zero errors) - Self-test: drill the deck once a day for three days; by day three you should clear all five gotchas from memory — that's the acceptance test for you, not just the code
Stretch goal: a pytest suite covering the scheduler's edges (streak
reset, empty deck, all-cards-future), plus a --stats flag printing a streak
histogram built with a dict comprehension.
14 · Interview radarHow This Shows Up in Interviews
Python screening questions show up even in AI-focused loops — usually in the first 15 minutes, as fluency checks. These five are the perennials:
"What's wrong with def f(x, items=[])?"
Strong answer The default is evaluated once, at
def time, and stored on the function object — so every call that uses the
default shares one list. Call f(1) twice and the second call sees whatever
the first appended. The fix is a None sentinel that creates a fresh list
inside the body, or default_factory in dataclasses.
Land it The bonus point: it's harmless with immutable defaults — the trap is specifically mutable ones.
"List vs tuple vs set — when and why?"
The real test Contracts, not trivia — can you say what each choice promises the reader?
Strong answer Each structure is a different contract:
- List is an ordered, growable sequence — the default when the collection can change size
- Tuple is a fixed-shape record: immutable, and therefore hashable, which is what lets it serve as a dict key
- Set buys O(1) membership tests and uniqueness, at the cost of order
Land it Choosing a tuple for a record signals "this shape is fixed" to readers — the choice communicates, not just computes.
"Generator vs list — what's the actual trade?"
Strong answer The trade is memory and laziness against
reusability. A generator holds one element alive at a time and computes values on
demand, which is exactly what streaming and huge files need — but it is single-pass
and has no len(). A list costs full materialization up front, and in
exchange buys random access and the ability to iterate again.
Land it Cite a real case: streaming LLM tokens as they arrive is generator territory; collecting a result list you'll re-read is a list. The deciding rule is two lines long.
"What does the GIL actually prevent?"
The real test Precision — can you name exactly what is serialized, and what isn't?
Strong answer The GIL serializes bytecode execution across threads, so it kills CPU parallelism but not I/O concurrency. The lock is released during blocking I/O, which is why threads and async still help for network-bound LLM work — a thread waiting on an API response isn't holding the GIL. For CPU-bound work, processes are the answer.
Land it Mention the 3.13+ free-threaded build as experimental — it shows currency.
"is vs ==?"
Strong answer is asks whether two names
point at the same object — identity — while == asks whether two values
are equal. Reserve is for singletons like None; everything
else gets ==.
Land it The judgment-check follow-up is
"why does x is 1000 sometimes work?" — small-int caching, an
implementation detail you should name and refuse to rely on.
Quick reference — Python fundamentals
- Choosing the Python toolchain
- Standard library first, uv for the project, mypy for hints, Pydantic where data crosses a border, NumPy for big number arrays. Add each one only when its problem shows up.
- Names are references
- A name points at an object; it does not contain it. Assignment rebinds the name and copies nothing — which explains most surprising Python behaviour.
- The mutable default trap
- A default argument is evaluated once, at definition.
def f(x=[])shares one list across every call. UseNone. - iteration protocol
- Anything with
__iter__can be looped over. A generator produces values lazily, one at a time, and never builds the whole list. Which one to reach for comes down to two lines. - comprehensions
- The idiomatic way to build a list, dict or set from another iterable. Read them as “what I want, for each thing, when a condition holds”.
- EAFP
- Easier to ask forgiveness than permission — try it and catch the error, rather than checking first. This is Python's style, not a shortcut.
- context manager
withguarantees cleanup even when something raises. Use it for every file, connection and lock.- GIL
- One thread runs Python bytecode at a time. So: threads or async for I/O-bound work, processes for CPU-bound work — the rule, measured.
- Passing an argument
- A call runs parameter = argument, so the function gets a second arrow to your object. Mutations are shared; rebinding is private, and nothing is copied.
+=on a list- Extends the same object, so every name sees the new item;
x = x + ybuilds a new list. On an int, a str or a tuple,+=always builds a new object. - numpy array
- One block of raw numbers of one type. About 4.5 times smaller than a list of the same ints; its
+adds, and its slices are views. - vectorised
- One operation for the whole array, looped in numpy's compiled code instead of Python's eval loop. It loses on a handful of values, on element-by-element loops and on one-at-a-time growth.
15 · RecapWhat You Can Do Now
- You can choose list, tuple, dict, or set deliberately — and defend the choice in review
- You can read and write comprehensions,
enumerate/zip, andsorted(key=…)at full reading speed - You can explain the iteration protocol and write a generator, knowing exactly when its body runs
- You can build a decorator from scratch — and recognize the shape in pytest, FastMCP, and FastAPI before those modules introduce it
- You can model data with
@dataclassand say precisely when Pydantic earns its install - You can handle errors EAFP-style with narrow excepts and chained raises, and explain what
withguarantees - You can annotate a function fully and run mypy clean — the habit every course lab assumes
- You can name all five classic gotchas from memory and spot them in someone else's diff
- You can say exactly what a function receives when you pass it a list, and predict whether the caller will see the change
- You can explain why one numpy line beats a Python loop, and name the cases where it does not
From this appendix: close the page and write, from memory, the
mutable-default gotcha and both fixes (the None sentinel and
default_factory) — then check yourself against gotchas.py.
And a forward reference: open Module 00 and find Fig 0.1 — the inversion
diagram, the course's first real idea. Read it and the code beneath it. Every Python construct
in that code is now one you know. You're ready to read it.