Every operator, loop, with block and attribute access is a call to a special method looked up on the object's type, with a fixed order of fallbacks when the method is missing or declines; implement the methods and your class behaves like a built-in, and almost every Python surprise is one of these lookups doing exactly what the rules say.
Five pieces of syntax, five lookups on the type: Fig. 1 draws each as a stack of the places Python tries, lowest first; a lookup climbs until one of them answers. Each climb is a real run of d2_dispatch.py (CPython 3.14.8), which logged every method Python called; the rules are the language reference's Data model chapter. The Data model explorer in section 1 replays 19 such lookups step by step from that run.
v + 1, a == b, for x in xs, obj.attr and with m as r, each a stack of places to try. The bottom plate (blue) is the special method on the type, and runs first; a higher plate is tried only if every plate below is missing or declines. with is the exception: it always climbs all three.v + 1: the left side declines, the right side answers. In 5 + A(2), int.__add__ does not know A and returns NotImplemented (inside C, so nothing is logged); Python then tries the right operand's reflected method, and the run logged call A.__radd__(A(2), 5) and the result A(7). Had both declined, the top plate: TypeError (section 1).a == b: both decline, identity answers. In E(1) == '1' the run logged call E.__eq__(E(1), '1') returning NotImplemented; str.__eq__ declines too, in C; so Python compares identities, a is b: False, never an error.for: no __iter__, so the old sequence protocol. Old defines only __getitem__, so list(Old()) called it with 0, 1, 2 and 3; the IndexError at 3 ends the loop, and the list is [0, 10, 20]. A class with __iter__ is answered by the bottom plate: __next__ until StopIteration (section 3).obj.attr: every place misses, so __getattr__. For o.missing there is no data descriptor on the type, no entry in o.__dict__ and nothing on the class, so the run logged call K.__getattr__('missing'), which returned 'made up for missing'. Without __getattr__, the top plate: AttributeError. Fig. 7 in section 5 climbs this stack for every outcome.with: enter, body, exit, always. __enter__ returned 'resource', bound to r; the body raised ValueError('boom'); __exit__ received it and returned True, which swallows the exception, so the function went on and returned 'after the with' (section 7).You need: Python: the essentials (names point at objects, aliasing, mutable default arguments). Type hints that describe these protocols (Protocol, Iterator[T]) are on Python: typing, uv, packaging and the toolchain; this page is what happens when the code runs.
__add__ that syntax calls for you.with, +); no base class needed.NotImplementedsuper() walk.__get__ (data descriptor: also __set__) that runs on attribute access; property, methods and slots are descriptors.except*.The data model is the chapter of the language reference that says which method Python calls for each piece of syntax (Data model; the old page called it "the single highest-value document in Python", and it is). You almost never call these dunder methods yourself; the syntax does.
| You write | Python calls | Fallback if it is missing |
|---|---|---|
len(x) | type(x).__len__(x) | TypeError; the result must be an int ≥ 0 |
bool(x), if x: | __bool__ | __len__() != 0, else always true |
for v in x, list(x) | __iter__, then __next__ until StopIteration | __getitem__(0), (1), ... until IndexError |
v in x | __contains__ | iterate and compare with == |
x[k], x[k] = v | __getitem__, __setitem__ | TypeError |
a + b | a.__add__(b) | if it returns NotImplemented: b.__radd__(a), then TypeError |
a += b | a.__iadd__(b) | a = a + b |
a == b | a.__eq__(b) | b.__eq__(a), then identity (a is b) |
hash(x), dict key, set member | __hash__ | identity-based hash; set to None (unhashable) if you define __eq__ alone |
with x as r: | __enter__, then __exit__(type, value, tb) | TypeError |
x.attr | type(x).__getattribute__ (descriptors, then x.__dict__, then the class) | __getattr__, then AttributeError |
repr(x), str(x), f"{x}" | __repr__ (for developers), __str__ (for users), __format__ | __str__ falls back to __repr__ |
A small vector class implements a handful of these, and the built-ins start working. Nothing inherits from anything: Python's polymorphism is by protocol (the methods you have), not by declared parent class.
class Vec: def __init__(self, *xs): self.xs = tuple(xs) def __repr__(self): # what the REPL and debuggers show return f"Vec{self.xs}" def __len__(self): # len(v) return len(self.xs) def __iter__(self): # for, list(), unpacking, sum() return iter(self.xs) def __getitem__(self, i): # v[i], v[1:] return self.xs[i] def __eq__(self, other): # == if not isinstance(other, Vec): return NotImplemented # "I don't know": let Python try the other side return self.xs == other.xs def __hash__(self): # dict keys, set members; must agree with == return hash(self.xs) def __add__(self, other): # v + w if not isinstance(other, Vec): return NotImplemented return Vec(*(a + b for a, b in zip(self.xs, other.xs, strict=True))) def __radd__(self, other): # 0 + v, which sum() does first return self if other == 0 else NotImplemented def __bool__(self): # if v: return any(self.xs) v, w = Vec(1, 2), Vec(3, 4) print(v + w, len(v), list(v), 2 in v, v[-1]) print(sum([v, w, Vec(10, 10)])) print(v == Vec(1, 2), len({v, Vec(1, 2)}), bool(Vec(0, 0))) print(v == (1, 2)) try: v + 1 except TypeError as e: print("TypeError:", e)
Vec(4, 6) 2 [1, 2] True 2 Vec(14, 16) True 1 False False TypeError: unsupported operand type(s) for +: 'Vec' and 'int'
The last three lines are the dispatch rules at work. sum() starts from the integer 0, so it first computes 0 + Vec(1, 2); int.__add__ does not know Vec and returns NotImplemented, so Python tries the right operand's __radd__. v == (1, 2) is False rather than an error because both sides returned NotImplemented and Python fell back to identity. And v + 1 raises TypeError only after both sides declined.
NotImplemented is not NotImplementedErrorNotImplemented means "I do not handle this type; ask the other operand". Raising NotImplementedError means "this abstract method was not written" and stops the dispatch dead. Mixing them up is a common bug in operator methods.x.__len__ = ... on one object does nothing for len(x). This lets CPython skip the instance dict on every operator.__eq__ and __hash__ travel together. "A class that overrides __eq__() and does not define __hash__() will have its __hash__() implicitly set to None" (same page). Objects that compare equal must have equal hashes, and a hash must not change while the object is in a dict or set; that is why mutable built-ins are unhashable and why a dict key should be immutable.Predict both before revealing: the first class defines nothing, the second only __eq__.
class P: def __init__(self, x): self.x = x print(P(1) == P(1), len({P(1), P(1)}))
False 2
class P: def __init__(self, x): self.x = x def __eq__(self, o): return self.x == o.x print({P(1)})
TypeError: cannot use 'P' as a set element (unhashable type: 'P')
Without __eq__, == falls back to identity, so two equal-looking objects are different set members. With __eq__ alone, the class loses its hash.
code/d2_dispatch.py (CPython 3.14.8); grey rows happen inside C, where nothing can log; blue is the result, orange an exception.Pick an expression and Fig. 2 replays it; the steps below say why each call happens, and the card states the rule at the last step. Scenarios come in pairs that differ in one detail: predict the second of each pair before it plays.
"""Run each data-model scenario and record which special methods Python called, in order. The Data model tab replays these traces; everything in them is printed by real calls.""" import json, sys LOG = [] def log(msg): LOG.append(msg) def scenario(fn): LOG.clear() try: r = fn() LOG.append(f"result: {r!r}") except Exception as e: LOG.append(f"raises {type(e).__name__}: {e}") return list(LOG) out = {} # 1. a + b, both A, A.__add__ handles it class A: def __init__(self, n): self.n = n def __repr__(self): return f"{type(self).__name__}({self.n})" def __add__(self, o): log(f"call {type(self).__name__}.__add__({self!r}, {o!r})") if not isinstance(o, A): log(" -> NotImplemented"); return NotImplemented return A(self.n + o.n) def __radd__(self, o): log(f"call {type(self).__name__}.__radd__({self!r}, {o!r})") if isinstance(o, int): return type(self)(self.n + o) log(" -> NotImplemented"); return NotImplemented out["add_same"] = scenario(lambda: A(1) + A(2)) # 2. left side gives up: int + A out["add_reflected"] = scenario(lambda: 5 + A(2)) # 3. subclass on the right that overrides __radd__ goes FIRST class B(A): def __radd__(self, o): log(f"call B.__radd__({self!r}, {o!r})") return B(self.n + o.n + 100) out["add_subclass"] = scenario(lambda: A(1) + B(2)) # 4. nobody handles it class C: def __repr__(self): return "C()" out["add_fail"] = scenario(lambda: A(1) + C()) # 5. == with NotImplemented on both sides falls back to identity class E: def __init__(self, n): self.n = n def __repr__(self): return f"E({self.n})" def __eq__(self, o): log(f"call E.__eq__({self!r}, {o!r})") if not isinstance(o, E): log(" -> NotImplemented"); return NotImplemented return self.n == o.n out["eq_fallback"] = scenario(lambda: E(1) == "1") out["eq_same"] = scenario(lambda: E(1) == E(1)) # 6. defining __eq__ without __hash__ makes instances unhashable out["hash_none"] = scenario(lambda: (log(f"# E.__dict__['__hash__'] is {E.__dict__['__hash__']!r}"), hash(E(1)))[1]) # 7. len() looks __len__ up on the TYPE, never on the instance class L: def __len__(self): log("call L.__len__"); return 3 x = L() x.__len__ = lambda: 99 out["len_type"] = scenario(lambda: (log("# x.__len__ = lambda: 99 was set on the instance"), len(x))[1]) class Neg: def __len__(self): log("call Neg.__len__ -> -1"); return -1 out["len_negative"] = scenario(lambda: len(Neg())) # 8. bool() falls back to __len__, then to True class OnlyLen: def __len__(self): log("call OnlyLen.__len__ -> 0"); return 0 class Nothing: pass out["bool_len"] = scenario(lambda: bool(OnlyLen())) out["bool_default"] = scenario(lambda: (log("# class Nothing has no __bool__ and no __len__"), bool(Nothing()))[1]) # 9. iteration falls back to the old __getitem__ protocol class Old: def __getitem__(self, i): log(f"call Old.__getitem__({i})") if i >= 3: log(" -> raises IndexError: iteration stops"); raise IndexError(i) return i * 10 out["iter_getitem"] = scenario(lambda: list(Old())) # 10. `in` without __contains__ scans __iter__ class It: def __iter__(self): log("call It.__iter__") for v in (1, 2, 3): log(f" yields {v}"); yield v out["contains_iter"] = scenario(lambda: 2 in It()) # 11. with: __enter__, body, __exit__ (a true return value swallows the exception) class Ctx: def __init__(self, swallow): self.swallow = swallow def __enter__(self): log("call Ctx.__enter__"); return "resource" def __exit__(self, et, ev, tb): log(f"call Ctx.__exit__({et.__name__ if et else None}, {ev!r}, tb) -> {self.swallow}") return self.swallow def body(swallow): with Ctx(swallow) as r: log(f"body: r = {r!r}; raise ValueError('boom')") raise ValueError("boom") return "after the with" out["with_propagate"] = scenario(lambda: body(False)) out["with_swallow"] = scenario(lambda: body(True)) # 12. attribute lookup order: data descriptor > instance __dict__ > non-data descriptor/class attr > __getattr__ class Data: def __get__(self, obj, owner): log(f"call Data.__get__(o, {owner.__name__})"); return "from data descriptor" def __set__(self, obj, v): log("Data.__set__") class NonData: def __get__(self, obj, owner): log(f"call NonData.__get__(o, {owner.__name__})"); return "from non-data descriptor" class K: d = Data() nd = NonData() plain = "class attribute" def __getattr__(self, name): log(f"normal lookup failed: call K.__getattr__({name!r})"); return f"made up for {name}" o = K() o.__dict__.update(d="instance dict d", nd="instance dict nd") out["attr_data"] = scenario(lambda: o.d) out["attr_instance"] = scenario(lambda: (log("# o.__dict__ has 'nd'; NonData has no __set__"), o.nd)[1]) out["attr_class"] = scenario(lambda: (log("# 'plain' is a str on the class, not in o.__dict__"), o.plain)[1]) out["attr_getattr"] = scenario(lambda: o.missing) json.dump(out, sys.stdout, indent=1) print()
print(bool([]), bool([0]), bool(''), bool(' '), bool(0.0), bool(None))
False True False True False False
print(1 < 2 < 3, 3 > 2 > 1 == 1, (1 < 2) < 3, 1 == 1.0 == True)True True True True
d = {1: 'int', 1.0: 'float', True: 'bool'}
print(d){1: 'bool'}1 < 2 < 3 means 1 < 2 and 2 < 3; (1 < 2) < 3 compares True < 3, and True == 1. In the dict, 1, 1.0 and True are equal and hash equally, so they are one key: the first key object stays and the last value wins.
sorted, sum, dict, f-strings, with, PyTorch's __torch_function__, NumPy's __array__.+ should combine, == should compare. Prefer a dataclass (section 5) when you only need __init__, __repr__ and __eq__.Assignment never copies (the essentials page's first fact). So two questions decide most "who changed my list?" bugs: what a copy copies, and what a function call hands over.
code/n7_graph.py: it runs each line with exec and labels every list by id() in order of first appearance. Ints are drawn as values.A shallow copy (x.copy(), list(x), x[:], copy.copy) makes a new outer container whose slots point at the same inner objects. A deep copy (copy.deepcopy) copies recursively, keeping a memo so that an object shared twice in the original is shared twice in the copy too. Predict what copy1 prints after line 4 in each mode, then let Fig. 3 run the five lines: the boxes are CPython's real objects, labelled by id() as the program ran.
row = [1, 2]: one list object, L1, and the name row pointing at it.grid = [row, row]: a new list L2 whose two slots both point at L1. Nothing was copied; L1 now has three references (row and two slots).copy1 = grid.copy(): a new outer list L3, but its slots point at the same L1. A shallow copy copies one level.grid[0].append(3) mutates L1, and every path to L1 sees it: row, both slots of grid and both slots of copy1.grid.append([9]) changes only the outer list L2. L3 is a different outer list, so copy1 still has two slots.row = [1, 2]: one list object, L1.grid = [row, row]: L2 with two slots pointing at L1.copy1 = copy.deepcopy(grid): new lists all the way down, L3 and a new inner list L4. Both slots of L3 point at the one L4: deepcopy keeps a memo, so sharing inside the original is reproduced, not multiplied.grid[0].append(3) mutates L1; copy1 is untouched, because L4 is a separate object.grid.append([9]) changes L2 only.9 0 [[1, 0], [1, 0], [1, 0]] [[1, 0], [0, 0], [0, 0]]
import copy grid = [[0, 0], [0, 0]] shallow = grid.copy() # new outer list, SAME inner lists deep = copy.deepcopy(grid) # new lists all the way down grid[0][0] = 9 print(shallow[0][0], deep[0][0]) rows = [[0] * 2] * 3 # three references to ONE inner list rows[0][0] = 1 print(rows) rows = [[0] * 2 for _ in range(3)] # three separate lists rows[0][0] = 1 print(rows)
grid = [[]] * 3
grid[0].append('x')
print(grid)[['x'], ['x'], ['x']]
[[0] * n] * m trap* on a list repeats references, not objects: three rows that are one row. Build nested lists with a comprehension. The same mistake inside a model config (one dict shared by every layer) is harder to see.Python passes a reference to the object (sometimes called "call by sharing"). A function can mutate the caller's object, but rebinding its own parameter name changes nothing outside. Default values are evaluated once, when def runs, so a mutable default is shared by every call.
def add_item(xs): xs.append("new") # mutates the object the caller passed def replace(xs): xs = ["other"] # rebinds the local name only items = ["a"] add_item(items) replace(items) print(items) def bad(x, acc=[]): # the default list is built ONCE, at def time acc.append(x) return acc print(bad(1), bad(2)) def good(x, acc=None): if acc is None: acc = [] acc.append(x) return acc print(good(1), good(2))
['a', 'new'] [1, 2] [1, 2] [1] [2]
+= is a method call tooa += b calls a.__iadd__(b) when the type has it (lists do: they extend in place) and falls back to a = a + b when it does not (tuples, ints, strings: a new object, rebound to the name). Predict, then reveal:
a = (1, 2) b = a a += (3,) print(a, b)
(1, 2, 3) (1, 2)
t = ([1], 2) try: t[0] += [3] # list += mutates in place, THEN tuple item assignment fails except TypeError as e: print("TypeError:", e) print(t) cache = {} try: cache[[1, 2]] = "x" # a list cannot be a dict key except TypeError as e: print("TypeError:", e) cache[(1, 2)] = "x" # a tuple of hashables can print(cache)
TypeError: 'tuple' object does not support item assignment
([1, 3], 2)
TypeError: cannot use 'list' as a dict key (unhashable type: 'list')
{(1, 2): 'x'}The tuple case is worth reading twice: t[0] += [3] is t[0] = t[0].__iadd__([3]). The list's in-place add succeeds and mutates the list; then the assignment back into the tuple fails. The error is real and so is the change.
The dict-key error message is new in 3.14 (What's new in 3.14); 3.13 said only "unhashable type: 'list'":
TypeError: 'tuple' object does not support item assignment
([1, 3], 2)
TypeError: unhashable type: 'list'
{(1, 2): 'x'}xs = [1, 2, 2, 3] for x in xs: if x == 2: xs.remove(x) # shifts the list under the running iterator print(xs) xs = [1, 2, 2, 3] xs = [x for x in xs if x != 2] # build a new list instead print(xs) d = {"a": 1, "b": 2} try: for k in d: d[k + "2"] = 0 except RuntimeError as e: print("RuntimeError:", e)
[1, 2, 3] [1, 3] RuntimeError: dictionary changed size during iteration
An iterable has __iter__, which returns a fresh iterator each time; an iterator is the one-pass cursor: __next__ returns the next item or raises StopIteration, and its __iter__ returns itself. A list is an iterable; iter(list) is an iterator. The difference shows up when you loop twice (Iterator types).
nums = [1, 2, 3] it = iter(nums) # list.__iter__ returns a NEW list_iterator print(type(it).__name__, next(it), next(it), next(it)) try: next(it) except StopIteration: print("StopIteration: the iterator is used up") squares = (n * n for n in nums) # a generator is an iterator: one pass only print(sum(squares), sum(squares)) print(sum(nums), sum(nums)) # a list is an iterable: each for/sum gets a fresh iterator
list_iterator 1 2 3 StopIteration: the iterator is used up 14 0 6 6
g = (x * 2 for x in range(3)) print(list(g), list(g))
[0, 2, 4] []
Calling a generator function (one containing yield) runs none of its body; it returns a generator, an iterator whose __next__ runs the body until the next yield, hands that value out, and freezes the function's local variables until it is asked again. (f(x) for x in xs) is the one-line form.
Chain generator stages and items flow through the whole chain one at a time; chain list-returning stages and each finishes before the next begins, holding every intermediate result. The program below does both on three lines of a chat log (the root page's running example: count tokens per user). Predict in which order the lazy version prints "read", "parse" and "count", then play Fig. 4 in each mode: every step is a stretch of the lines g2_order.py printed, in order.
Eager stages each finish before the next starts; lazy stages pass one line all the way through
read {"user": "a", read oops, read {"user": "b": all three lines go into one list before anything downstream starts. Held: 3 items.parse a, parse skip, parse b: the bad line is dropped, and the read list stays alive until parsing returns. Held: 5 items (3 lines, 2 messages).count a 2, count b 1; the read list is gone, the parsed one is still held. Held: 4 items (2 messages, 2 counts).sum adds the last list: total 3. Every stage ran to the end before the next began, so each intermediate list existed in full.sum() pulls; nothing ran before. sum asks count_gen for a value, which asks parse_gen, which asks read_gen (the grey dots, flowing backwards); only then is one line read. Printed read {"user": "a".parse a, then count a 2: sum holds 2 before the second line has been read.read oops, parse skip: parse_gen drops it and at once asks read_gen for the next line; nothing reaches count_gen.read {"user": "b", parse b, count b 1: the sum is 3.read_gen runs out of lines and returns, which ends the for loop inside parse_gen with StopIteration; it returns in turn, and so on up to sum. At most one line was ever in flight, and no list was built."Held" counts items stored in the lists that exist at that moment: the eager version keeps each stage's whole list until the next stage has consumed it.
import json LINES = ['{"user": "a", "text": "hi there"}', 'oops', '{"user": "b", "text": "ok"}'] # Eager: each stage builds and returns a full list. Lazy: the same stages with yield. def read_list(lines): out = [] for line in lines: print(" read ", line[:12]); out.append(line) return out def parse_list(lines): out = [] for line in lines: try: msg = json.loads(line) except json.JSONDecodeError: print(" parse skip"); continue print(" parse ", msg["user"]); out.append(msg) return out def count_list(msgs): out = [] for m in msgs: n = len(m["text"].split()); print(" count ", m["user"], n); out.append(n) return out def read_gen(lines): for line in lines: print(" read ", line[:12]); yield line def parse_gen(lines): for line in lines: try: msg = json.loads(line) except json.JSONDecodeError: print(" parse skip"); continue print(" parse ", msg["user"]); yield msg def count_gen(msgs): for m in msgs: n = len(m["text"].split()); print(" count ", m["user"], n); yield n print("eager (lists):") print("total", sum(count_list(parse_list(read_list(LINES))))) print("lazy (generators):") print("total", sum(count_gen(parse_gen(read_gen(LINES)))))
eager (lists):
read {"user": "a"
read oops
read {"user": "b"
parse a
parse skip
parse b
count a 2
count b 1
total 3
lazy (generators):
read {"user": "a"
parse a
count a 2
read oops
parse skip
read {"user": "b"
parse b
count b 1
total 3At three lines the difference is cosmetic. At a million lines it is the difference between fitting in memory and not: the same token count, eager and lazy, with Python's own allocation tracker (tracemalloc) reporting the peak.
eager total=7000000 peak=108,190.2 KiB lazy total=7000000 peak= 1.1 KiB
"""Peak memory of the same token count, eager lists against a lazy generator pipeline. 1,000,000 synthetic lines made on the fly; tracemalloc measures Python allocations.""" import tracemalloc N = 1_000_000 def lines(): for i in range(N): yield f'{{"user": "u{i % 200:04d}", "text": "token number {i} here"}}' def eager(): rows = list(lines()) # every line in memory words = [len(r.split()) for r in rows] # plus a list of counts return sum(words) def lazy(): return sum(len(r.split()) for r in lines()) # one line at a time for fn in (eager, lazy): tracemalloc.start() total = fn() cur, peak = tracemalloc.get_traced_memory() tracemalloc.stop() print(f"{fn.__name__:5} total={total} peak={peak / 1024:9,.1f} KiB")
The lazy pipeline peaked at about 1.1 KiB because only one line exists at a time; the eager one held a million strings and a million counts (about 106 MiB). Laziness also lets a pipeline start producing before its input ends, which is what streaming is.
An LLM SDK's streaming response is a generator (or, in async code, an async generator): each iteration waits for the next chunk from the network. The part to get right is cleanup. If the consumer stops early, the generator is left paused inside its loop; its finally block runs when the generator is closed, either explicitly with close() (which raises GeneratorExit at the paused yield) or when it is garbage-collected. Close it yourself, or wrap it in contextlib.closing, when it holds a connection.
[open connection] [close connection] 'Python generators stream lazily.' [open connection] consumer stopped [close connection] after close
"""A generator that streams tokens the way an LLM client does, and what happens when the consumer stops early: the generator's finally block still runs.""" import time def fake_model(prompt): tokens = ["Py", "thon", " gener", "ators", " stream", " lazily", "."] print("[open connection]") try: for t in tokens: time.sleep(0.01) # stands in for network latency yield t finally: print("[close connection]") # runs on exhaustion, on close(), and on garbage collection out = [] for tok in fake_model("hi"): out.append(tok) print(repr("".join(out))) stream = fake_model("hi") for i, tok in enumerate(stream): if i == 2: break # stop after three tokens print("consumer stopped") stream.close() # raises GeneratorExit inside the generator print("after close")
yield from, and generators that receive values (how asyncio began)yield from sub hands control to a sub-generator until it finishes, passing values (and anything sent in) straight through, and evaluates to the sub-generator's return value (PEP 380). Generators can also receive: g.send(v) resumes the generator and makes the paused yield expression evaluate to v. This "coroutine" use of generators is how asyncio was first built; today you will meet it mostly in library internals. Coroutines and the event loop are on Python: concurrency, asyncio and the GIL.
def flatten(xs): for x in xs: if isinstance(x, list): yield from flatten(x) # delegate to a sub-generator else: yield x print(list(flatten([1, [2, [3, 4]], 5]))) def worker(): total = 0 while (x := (yield)) is not None: # receives values sent in total += x return total # becomes the value of `yield from` def manager(results): results.append((yield from worker())) res = [] g = manager(res) next(g) # run to the first yield for v in (10, 20, 30): g.send(v) try: g.send(None) except StopIteration: pass print(res)
[1, 2, 3, 4, 5] [60]
import itertools as it print(list(it.islice(it.count(10, 5), 4))) # lazy slice of an infinite iterator print(list(it.batched(range(7), 3))) # 3.12+: fixed-size chunks print(list(it.chain([1, 2], (3,), "ab"))) users = ["b", "a", "b", "a"] print([(k, len(list(g))) for k, g in it.groupby(users)]) # groups RUNS, not keys print([(k, len(list(g))) for k, g in it.groupby(sorted(users))]) # sort first a, b = it.tee(iter([1, 2, 3])) print(list(a), list(b))
[10, 15, 20, 25]
[(0, 1, 2), (3, 4, 5), (6,)]
[1, 2, 3, 'a', 'b']
[('b', 1), ('a', 1), ('b', 1), ('a', 1)]
[('a', 2), ('b', 2)]
[1, 2, 3] [1, 2, 3]itertools.batched is new in 3.12 and is the idiom for "send requests in groups of N". groupby groups consecutive runs, not equal keys, so sort first (the classic bug: per-user totals that list a user twice). tee buffers everything one copy has read and the other has not, so it can quietly hold as much memory as a list.
print(list(zip('abc', [1, 2]))) try: print(list(zip('abc', [1, 2], strict=True))) except ValueError as e: print('ValueError:', e)
[('a', 1), ('b', 2)]
ValueError: zip() argument 2 is shorter than argument 1calls = [] m = map(calls.append, [1, 2, 3]) print(calls) list(m) print(calls)
[] [1, 2, 3]
len: materialise a list once, deliberately.def is a statement that runs: it builds a function object (code, defaults, a reference to the enclosing scope) and binds it to a name. Closures, decorators and caches all follow from that.
A function defined inside another can read the outer function's variables after the outer one has returned; it keeps them in cells, visible as __closure__. Two rules cause most closure bugs. A closure captures the variable, not its value at the time, so it sees whatever the variable holds when it finally runs (late binding). And any assignment to a name inside a function makes that name local to the whole function, unless you declare it nonlocal (enclosing function) or global (module).
def make_counter(): count = 0 def inc(): nonlocal count # without this, count += 1 is an UnboundLocalError count += 1 return count return inc c = make_counter() print(c(), c(), c(), c.__closure__[0].cell_contents) fs = [lambda: i for i in range(3)] # every lambda reads the SAME variable i, later print([f() for f in fs]) fs = [lambda i=i: i for i in range(3)] # a default is evaluated now: one value each print([f() for f in fs]) def broken(): total = 0 def add(x): total += x # assignment makes total local to add add(1) try: broken() except UnboundLocalError as e: print("UnboundLocalError:", e)
1 2 3 3 [2, 2, 2] [0, 1, 2] UnboundLocalError: cannot access local variable 'total' where it is not associated with a value
fs = [] for i in range(3): fs.append(lambda: i * 10) print([f() for f in fs])
[20, 20, 20]
x = 1
def f():
print(x)
x = 2
f()UnboundLocalError: cannot access local variable 'x' where it is not associated with a value
@timed above def work means exactly work = timed(work): a decorator takes a function and returns a replacement. Decorators stack bottom-up: the one nearest def is applied first. Always wrap with functools.wraps, or the replacement loses the original's name, docstring and signature (and tools such as pytest, FastAPI and debuggers see "wrapper").
work took 0.040 s 333332833333500000 work Sum of squares. work wrapper None
import functools, time def timed(fn): # a decorator: takes a function, returns one @functools.wraps(fn) # copy __name__, __doc__, __wrapped__ ... def wrapper(*args, **kwargs): t0 = time.perf_counter() try: return fn(*args, **kwargs) finally: print(f"{fn.__name__} took {time.perf_counter() - t0:.3f} s") return wrapper @timed # same as: work = timed(work) def work(n): """Sum of squares.""" return sum(i * i for i in range(n)) print(work(1_000_000)) print(work.__name__, work.__doc__, work.__wrapped__.__name__) def no_wraps(fn): def wrapper(*a, **k): return fn(*a, **k) return wrapper @no_wraps def other(): """Docs that will be lost.""" print(other.__name__, other.__doc__)
def tag(t): def deco(fn): return lambda: f'<{t}>' + fn() + f'</{t}>' return deco @tag('b') @tag('i') def hi(): return 'hi' print(hi())
<b><i>hi</i></b>
A decorator with arguments, @retry(times=4), is one level deeper: retry(times=4) runs first and returns the actual decorator. This is the shape of a real retry helper for a model API: retry only errors that can succeed on a second try (connection resets, timeouts, rate limits), with exponential backoff and random jitter, and never retry a 400.
import functools, random, time def retry(times=3, base_delay=0.01, on=(ConnectionError, TimeoutError)): """A decorator WITH arguments is a function that returns a decorator.""" def decorate(fn): @functools.wraps(fn) def wrapper(*args, **kwargs): for attempt in range(1, times + 1): try: return fn(*args, **kwargs) except on as e: if attempt == times: raise # out of attempts: re-raise the last error delay = base_delay * 2 ** (attempt - 1) * random.uniform(0.5, 1.5) print(f"attempt {attempt} failed ({e!r}); retrying in {delay * 1000:.0f} ms") time.sleep(delay) return wrapper return decorate random.seed(0) calls = {"n": 0} @retry(times=4) def flaky_completion(prompt): calls["n"] += 1 if calls["n"] < 3: raise ConnectionError("upstream reset") return f"answer to {prompt!r}" print(flaky_completion("hello")) @retry(times=2) def bad_request(): raise ValueError("400: bad request") # not in `on`: never retried try: bad_request() except ValueError as e: print("not retried:", e)
attempt 1 failed (ConnectionError('upstream reset')); retrying in 13 ms
attempt 2 failed (ConnectionError('upstream reset')); retrying in 25 ms
answer to 'hello'
not retried: 400: bad requestBackoff, jitter and retry budgets as a reliability pattern (and why retries without them make outages worse) are on Reliability engineering. In production use a library such as tenacity or the retry built into your SDK client; the point here is that it is twenty lines of ordinary Python.
functools.cache and lru_cache@functools.cache (unbounded) and @functools.lru_cache(maxsize=N) (least recently used entries evicted) store results keyed by the arguments (functools). Recursive Fibonacci makes the effect visible: 81 calls instead of 242,785 for a smaller input.
23416728348467685 calls: 81 CacheInfo(hits=78, misses=81, maxsize=None, currsize=81) without the cache, fib(25) makes 242785 calls TypeError: unhashable type: 'list'
import functools calls = 0 @functools.cache # = lru_cache(maxsize=None) def fib(n): global calls calls += 1 return n if n < 2 else fib(n - 1) + fib(n - 2) print(fib(80), "calls:", calls) print(fib.cache_info()) calls = 0 def fib_plain(n): global calls calls += 1 return n if n < 2 else fib_plain(n - 1) + fib_plain(n - 2) fib_plain(25) print("without the cache, fib(25) makes", calls, "calls") @functools.lru_cache(maxsize=128) def embed(text): return len(text) try: embed(["not", "hashable"]) # arguments become a dict key except TypeError as e: print("TypeError:", e)
__hash__ rule). The cache holds strong references to every argument and result, so lru_cache on a method keeps each self alive "until they age out of the cache or until the cache is cleared" (with cache, which never evicts, for the life of the process); for methods without arguments the Python FAQ suggests functools.cached_property, which lives and dies with the instance. And a cache is invisible state: a function whose result depends on time, a file or a random seed must not be cached.A / in the parameter list makes everything before it positional-only; a * makes everything after it keyword-only. *args collects extra positional arguments into a tuple and **kwargs extra keyword arguments into a dict. Keyword-only parameters are the cheap way to stop callers from passing 0.2 to the wrong slot.
def call(model, /, prompt, *, temperature=1.0, **extra): # ^ positional-only ^ keyword-only after * return f"{model} {prompt!r} t={temperature} extra={extra}" print(call("m1", "hi", temperature=0.2, top_p=0.9)) print(call("m1", prompt="hi")) for bad in ('call(model="m1", prompt="hi")', 'call("m1", "hi", 0.2)'): try: eval(bad) except TypeError as e: print("TypeError:", e) def forward(*args, **kwargs): # collect anything... return call(*args, **kwargs) # ...and spread it back out print(forward("m2", "yo", temperature=0))
m1 'hi' t=0.2 extra={'top_p': 0.9}
m1 'hi' t=1.0 extra={}
TypeError: call() missing 1 required positional argument: 'model'
TypeError: call() takes 2 positional arguments but 3 were given
m2 'yo' t=0 extra={}The first error is worth a second look. Because call has **extra, the keyword model="m1" is not rejected as "positional-only passed as keyword"; it is accepted into extra, and the positional slot is then reported missing.
@app.get) written once.A class statement runs its body like a function body, collects the names it defined into a dict, and builds a class object from it. An instance stores its own attributes (usually in obj.__dict__); everything else, methods included, lives on the class and is found by looking up the chain of classes.
That chain is the method resolution order (MRO), Cls.__mro__, computed by the C3 linearisation algorithm (The Python 2.3 MRO): every class appears before its parents, and parents keep the order you listed them. super() means "the next class in the MRO of type(self)", not "my parent", which is what lets several mixins each run their part of setup exactly once (cooperative multiple inheritance). Fig. 5 plays c1_mro.py (its output is below the figure's section).
class Service(Logging, Caching); Logging and Caching both inherit from Base, and every class from object. The arrows point from a class to its parents: a graph, not a line.Service.__mro__ as ['Service', 'Logging', 'Caching', 'Base', 'object']: each class before its parents, parents in the order listed. Attribute lookup and super() climb this stack from the bottom.super() follows the stack, not the parent. Service().setup() printed Service.setup ->, Logging.setup ->, Caching.setup ->, Base.setup, each class once. Logging's super() reaches Caching, a class it never names, when self is a Service.Logging.__mro__ printed as ['Logging', 'Base', 'object'], so Logging().setup() on its own goes straight to Base, because Logging's own MRO has no Caching in it: Logging.setup ->, then Base.setup.class Bad(Base, Logging) lists Base before its own subclass, but C3 must put Logging before its parent Base. No order does both, so the class statement itself fails: TypeError: Cannot create a consistent method resolution order (MRO) for bases Base, Logging.['Service', 'Logging', 'Caching', 'Base', 'object'] Service.setup -> Logging.setup -> Caching.setup -> Base.setup ['Logging', 'Base', 'object'] Logging.setup -> Base.setup TypeError: Cannot create a consistent method resolution order (MRO) for bases Base, Logging
class Base: def setup(self): print("Base.setup") class Logging(Base): def setup(self): print("Logging.setup ->"); super().setup() class Caching(Base): def setup(self): print("Caching.setup ->"); super().setup() class Service(Logging, Caching): def setup(self): print("Service.setup ->"); super().setup() print([c.__name__ for c in Service.__mro__]) Service().setup() # super() means "next in the MRO of type(self)", not "my parent" print([c.__name__ for c in Logging.__mro__]) Logging().setup() try: class Bad(Base, Logging): # Base listed before its own subclass pass except TypeError as e: print("TypeError:", e)
class A: def who(self): return 'A' class B(A): def who(self): return 'B' + super().who() class C(A): def who(self): return 'C' + super().who() class D(B, C): def who(self): return 'D' + super().who() print(D().who())
DBCA
Use this sparingly. Mixins with cooperative super() calls are fine; deep hierarchies are rarely worth it. Composition (an object that holds a Cache and a Logger) is usually easier to read and test than inheriting from both; when to choose composition over inheritance is a design question, on Code design.
@dataclass writes __init__, __repr__ and __eq__ from the annotated class attributes (dataclasses). frozen=True forbids assignment and makes instances hashable; slots=True (3.10+) adds __slots__; order=True adds comparisons. Mutable defaults must go through field(default_factory=...); the decorator refuses the mistake outright (last error below).
Message(role='user', text='hi', tokens=1) True True
Message(role='user', text='hello', tokens=1)
FrozenInstanceError: cannot assign to field 'text'
{'model': 'small-model', 'messages': [{'role': 'user', 'text': 'hi', 'tokens': 1}]}
ValueError: mutable default <class 'list'> for field items is not allowed: use default_factory
('role', 'text', 'tokens') Falsefrom dataclasses import dataclass, field, asdict, replace @dataclass(frozen=True, slots=True) class Message: role: str text: str tokens: int = 0 @dataclass class Conversation: model: str messages: list[Message] = field(default_factory=list) # a fresh list per instance m = Message("user", "hi", 1) print(m, m == Message("user", "hi", 1), hash(m) == hash(Message("user", "hi", 1))) print(replace(m, text="hello")) try: m.text = "changed" except Exception as e: print(type(e).__name__ + ":", e) c = Conversation("small-model") c.messages.append(m) print(asdict(c)) try: @dataclass class Bad: items: list = [] except ValueError as e: print("ValueError:", e) print(Message.__slots__, hasattr(m, "__dict__"))
For data that crosses a boundary (JSON from an API, a config file) a dataclass checks nothing; its annotations are not enforced at run time. Use Pydantic there, which validates and converts; use dataclasses inside your program, where the type checker already guards the values.
__slots__ and what an object really costs__slots__ = ("user", "n") tells CPython to reserve fixed storage for exactly those attributes and not to create a per-instance __dict__. Measured on 100,000 small records with tracemalloc (each figure includes the 8-byte slot in the list that holds them), in Fig. 6.
Slots save 40 bytes per record here (96 against 56). The gap used to be larger: since 3.11 "Objects now require less memory due to lazily created object namespaces" (What's new in 3.11), so a plain instance no longer builds a full dict up front. The costs of slots: no new attributes at run time (the AttributeError below), and some care with multiple inheritance. Use them for classes with millions of instances; ignore them otherwise.
outputs/c3_sizes.txt (CPython 3.14.8, Python allocations only). The script is in the closed block below."""Memory for 100,000 small records, measured with tracemalloc (Python allocations only).""" import tracemalloc from collections import namedtuple from dataclasses import dataclass class Plain: def __init__(self, user, n): self.user, self.n = user, n class Slotted: __slots__ = ("user", "n") def __init__(self, user, n): self.user, self.n = user, n @dataclass class DC: user: str; n: int @dataclass(slots=True) class DCS: user: str; n: int NT = namedtuple("NT", "user n") USERS = [f"u{i:04d}" for i in range(200)] # shared strings, not counted per record N = 100_000 kinds = [("class", Plain), ("class + __slots__", Slotted), ("dataclass", DC), ("dataclass(slots=True)", DCS), ("namedtuple", NT), ("tuple", lambda u, n: (u, n)), ("dict", lambda u, n: {"user": u, "n": n})] for name, make in kinds: tracemalloc.start() rows = [make(USERS[i % 200], i % 250) for i in range(N)] # small ints are cached: no int allocation cur, _ = tracemalloc.get_traced_memory() tracemalloc.stop() del rows print(f"{name:22} {cur / N:6.1f} bytes per record")
class 96.1 bytes per record class + __slots__ 56.0 bytes per record dataclass 96.0 bytes per record dataclass(slots=True) 56.0 bytes per record namedtuple 80.0 bytes per record tuple 72.0 bytes per record dict 192.0 bytes per record
class S: __slots__ = ('x',) s = S() s.x = 1 s.y = 2
AttributeError: 'S' object has no attribute 'y' and no __dict__ for setting new attributes
property, methods and self workA descriptor is an object stored on a class that defines __get__ (and optionally __set__ and __delete__). When attribute lookup finds one on the class, it calls it instead of returning it (Descriptor guide). One with __set__ is a data descriptor, and the order is fixed: "data descriptors always override instance dictionaries. However, non-data descriptors can be overridden by instance dictionaries" (Invoking descriptors). Fig. 7 climbs the full lookup for obj.x (the fourth stack of Fig. 1) with the classes of two real runs.
obj.x Python tries: a data descriptor named x on type(obj) or its MRO (for example a property); otherwise obj.__dict__["x"]; otherwise a non-data descriptor (a plain function, which becomes a bound method) or plain class attribute; otherwise __getattr__, if the class defines it; otherwise AttributeError. The blocks are what d2_dispatch.py's class K and its instance o hold: K.d is a data descriptor, K.nd a non-data one, K.plain a string, and o.__dict__ has entries d and nd.o.d: the data descriptor wins. The first plate already holds d, and it has __set__, so the run logged call Data.__get__(o, K) and returned 'from data descriptor'; o.__dict__['d'], one plate up, is never consulted.o.nd: the instance dict beats a non-data descriptor. K.nd has no __set__, so the climb goes on to o.__dict__ and returns 'instance dict nd'; NonData.__get__ never runs. Methods are non-data descriptors, which is why obj.method = something shadows a method on one instance.o.plain: the class. Not a data descriptor and not in o.__dict__, so the value on the class is returned as is: 'class attribute'. This is how methods and class constants are found, and how a mutable class attribute ends up shared.o.missing: __getattr__, last. All three places miss, so the run logged call K.__getattr__('missing'), which returned 'made up for missing'. __getattr__ is called only after normal lookup fails (unlike __getattribute__, which runs for every access); use it for proxies and lazy attributes.c4_descriptor.py's Sampling. Its instance s holds only {'_temperature': 0.7, '_max_tokens': 256}; describe is a plain function on the class (third plate), and looking it up calls its __get__, which returns a bound method: the run printed function method, the type on the class and the type you get.temperature and max_tokens are Positive descriptors and budget is a property, all on the first plate, so assignment goes through them: ValueError: temperature must be > 0, got 0, and AttributeError: property 'budget' of 'Sampling' object has no setter instead of a new entry in s.__dict__.This one mechanism explains a lot of "magic". property is a data descriptor, which is why assigning to a read-only property fails instead of shadowing it (step 7). A function is a non-data descriptor: s.describe calls describe.__get__(s, Sampling), which returns a bound method that remembers s and passes it as self. Frameworks (Django fields, SQLAlchemy columns, Pydantic) are descriptors with validation inside, like the Positive below.
t=0.7 max=256 1024 {'_temperature': 0.7, '_max_tokens': 256}
ValueError: temperature must be > 0, got 0
AttributeError: property 'budget' of 'Sampling' object has no setter
function method
t=0.7 max=256 True True
False Trueclass Positive: """A reusable validated attribute: a data descriptor (it defines __set__).""" def __set_name__(self, owner, name): self.name = "_" + name def __get__(self, obj, owner): if obj is None: return self # accessed on the class itself return getattr(obj, self.name) def __set__(self, obj, value): if value <= 0: raise ValueError(f"{self.name[1:]} must be > 0, got {value}") setattr(obj, self.name, value) class Sampling: temperature = Positive() max_tokens = Positive() def __init__(self, temperature, max_tokens): self.temperature = temperature # goes through Positive.__set__ self.max_tokens = max_tokens @property # property is a data descriptor too def budget(self): return self.max_tokens * 4 def describe(self): return f"t={self.temperature} max={self.max_tokens}" s = Sampling(0.7, 256) print(s.describe(), s.budget, vars(s)) try: s.temperature = 0 except ValueError as e: print("ValueError:", e) try: s.budget = 1 except AttributeError as e: print("AttributeError:", e) # A method is a function stored on the class; looking it up on an instance binds it. f = Sampling.__dict__["describe"] print(type(f).__name__, type(s.describe).__name__) bound = f.__get__(s, Sampling) # exactly what s.describe does print(bound(), bound.__self__ is s, bound.__func__ is f) print(s.describe is s.describe, s.describe == s.describe) # a new bound method each time
obj.method() does not build a bound method (bytecode)The last line above shows that s.describe builds a new bound-method object each time. The direct call form obj.method() skips it: the compiler emits one LOAD_ATTR that pushes the function and self separately, shown as describe + NULL|self below, so no bound-method object is built; the optimisation was called LOAD_METHOD when it arrived in 3.7. Bytecode in general is on Python: CPython internals and performance.
import dis dis.dis("s.describe()") # the direct call form: method and self pushed separately
0 RESUME 0
1 LOAD_NAME 0 (s)
LOAD_ATTR 3 (describe + NULL|self)
CALL 0
RETURN_VALUEAnd the classic trap, a mutable class attribute, follows from the third plate of the lookup: reading a.tools finds the class's list; assigning a.tools = ... creates an instance entry that shadows it.
class Agent: tools = [] # ONE list, stored on the class, shared by all instances def __init__(self, name): self.name = name a, b = Agent("a"), Agent("b") a.tools.append("search") # finds Agent.tools via the class, mutates it print(b.tools, "tools" in vars(a)) a.tools = ["calc"] # assignment creates an instance attribute that shadows it print(a.tools, b.tools, Agent.tools)
['search'] False ['calc'] ['search'] ['search']
class C: n = 0 def bump(self): self.n += 1 a, b = C(), C() a.bump(); a.bump() print(a.n, b.n, C.n)
2 0 0
Protocol (on the typing page) instead of a base class when you only need "has these methods".__init_subclass__ covers most "run code when a subclass is defined" needs); mutable class attributes.An exception is an object; raise unwinds the stack until an except clause whose class matches (by isinstance, in the order written). Since 3.11 a try that raises nothing costs nothing ("zero-cost" exceptions, What's new in 3.11), so "ask forgiveness, not permission" (try it and catch the failure) is not a performance sin. How to design a library's errors (raise rather than return None, what to catch where) is on Code design; this section is the mechanics.
except Exception does not catchEverything derives from BaseException. Ordinary errors derive from its subclass Exception; four do not, on purpose, so that a broad except Exception: lets them through: KeyboardInterrupt (Ctrl-C), SystemExit (sys.exit()), GeneratorExit (section 3) and, since 3.8, asyncio.CancelledError. Predict which of the four lines say "caught":
import asyncio for exc in (ValueError, KeyboardInterrupt, asyncio.CancelledError, SystemExit): try: try: raise exc() except Exception: print(exc.__name__, 'caught by except Exception') except BaseException: print(exc.__name__, 'NOT caught by except Exception')
ValueError caught by except Exception KeyboardInterrupt NOT caught by except Exception CancelledError NOT caught by except Exception SystemExit NOT caught by except Exception
Give your own library one root exception so callers can catch "anything from this client" with one clause, and specific subclasses carrying data (here retry_after) for the cases callers handle differently.
except Exception catches one branch; Ctrl-C, sys.exit(), GeneratorExit and cancellation sit outside itissubclass answers and RateLimited.__mro__ are in the real output of e3_hierarchy.py below, whose classes form the blue branch.wait 1.5 ContextTooLong 10000 tokens > 8192 ['RateLimited', 'LLMError', 'Exception', 'BaseException', 'object'] False True True False
class LLMError(Exception): """Root of everything this client raises: callers can catch one type.""" class RateLimited(LLMError): def __init__(self, retry_after: float): super().__init__(f"rate limited, retry after {retry_after}s") self.retry_after = retry_after class ContextTooLong(LLMError): pass def complete(prompt_tokens): if prompt_tokens > 8192: raise ContextTooLong(f"{prompt_tokens} tokens > 8192") raise RateLimited(retry_after=1.5) for n in (100, 10_000): try: complete(n) except RateLimited as e: # most specific first print("wait", e.retry_after) except LLMError as e: # then the family print(type(e).__name__, e) print([c.__name__ for c in RateLimited.__mro__]) print(issubclass(KeyboardInterrupt, Exception), issubclass(KeyboardInterrupt, BaseException)) print(issubclass(TimeoutError, OSError)) import asyncio print(issubclass(asyncio.CancelledError, Exception))
Exception around a block that includes a KeyboardInterrupt-sensitive call". except Exception does not catch KeyboardInterrupt (output above: False True); the real trap is a bare except: or except BaseException:, which does, and so makes a program impossible to stop with Ctrl-C or to cancel in asyncio.raise ... fromRaising inside an except block records the original exception as __context__, and the traceback says "During handling of the above exception, another exception occurred", which reads like a second bug. raise NewError(...) from e sets __cause__ and says "The above exception was the direct cause", which is what you meant: translate a low-level error into your own while keeping the evidence. from None hides the original.
import json, sys, traceback class ConfigError(Exception): pass def load(text): try: return json.loads(text) except json.JSONDecodeError as e: raise ConfigError("config is not valid JSON") from e # explicit cause def load_sloppy(text): try: return json.loads(text) except json.JSONDecodeError: raise ConfigError("config is not valid JSON") # implicit context for fn in (load, load_sloppy): try: fn("{bad") except ConfigError as e: print(f"--- {fn.__name__}: __cause__={type(e.__cause__).__name__}, " f"__context__={type(e.__context__).__name__}, __suppress_context__={e.__suppress_context__}") traceback.print_exc(limit=0, file=sys.stdout) # limit=0: messages only
--- load: __cause__=JSONDecodeError, __context__=JSONDecodeError, __suppress_context__=True json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1) The above exception was the direct cause of the following exception: ConfigError: config is not valid JSON --- load_sloppy: __cause__=NoneType, __context__=JSONDecodeError, __suppress_context__=False json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1) During handling of the above exception, another exception occurred: ConfigError: config is not valid JSON
except* and notesConcurrent code can fail in several places at once. Since 3.11 an ExceptionGroup carries several exceptions, except* handles each matching subset (PEP 654), and asyncio.TaskGroup raises one when tasks fail. e.add_note(...) (PEP 678) attaches context without changing the exception's type.
timeouts: ['rerank failed']
bad values: ['embed failed']
ExceptionGroup('batch failed', [KeyError('a'), KeyError('c')])
ExceptionGroup('batch failed', [ValueError('b')])
KeyError('model') ["while reading config.yaml, section 'llm'"]import asyncio async def call(name, fail): await asyncio.sleep(0.01) if fail: raise fail(f"{name} failed") return name async def main(): try: async with asyncio.TaskGroup() as tg: # 3.11+: structured concurrency tg.create_task(call("search", None)) tg.create_task(call("rerank", TimeoutError)) tg.create_task(call("embed", ValueError)) except* TimeoutError as eg: # handles the TimeoutError part print("timeouts:", [str(e) for e in eg.exceptions]) except* ValueError as eg: # and, separately, the ValueError part print("bad values:", [str(e) for e in eg.exceptions]) asyncio.run(main()) eg = ExceptionGroup("batch failed", [KeyError("a"), ValueError("b"), KeyError("c")]) match, rest = eg.split(KeyError) print(repr(match), repr(rest), sep="\n") try: try: {}["model"] except KeyError as e: e.add_note("while reading config.yaml, section 'llm'") # 3.11+ raise except KeyError as e: print(repr(e), e.__notes__)
else and finallydef order(fail): try: print("try") if fail: raise ValueError("x") except ValueError: print("except") else: print("else (only when try raised nothing)") finally: print("finally (always)") order(False) order(True) def swallow(): try: raise RuntimeError("lost") finally: return "finally's return wins" # silently discards the exception print(swallow())
e4_finally.py:20: SyntaxWarning: 'return' in a 'finally' block return "finally's return wins" # silently discards the exception try else (only when try raised nothing) finally (always) try except finally (always) finally's return wins
A return inside finally throws away the exception in flight. Since 3.14 the compiler warns about it: "The compiler now emits a SyntaxWarning when a return, break, or continue statement have the effect of leaving a finally block" (PEP 765).
Under 3.13 the same file prints no warning:
try else (only when try raised nothing) finally (always) try except finally (always) finally's return wins
def f(): try: return 'try' finally: print('finally runs first') print(f())
finally runs first try
for n in [3, 5, 7]: if n % 2 == 0: print('found even'); break else: print('no break happened')
no break happened
A loop's else runs when the loop ended without break; it is the "not found" branch of a search.
raise ... from; log with the traceback (logger.exception) once, at the top.except:; except Exception: pass; catching around more code than the call that can fail; raising Exception("...") instead of a specific class.withwith m as r: calls m.__enter__(), binds its return value to r, runs the body, and then always calls m.__exit__(exc_type, exc, tb), with the exception if one was raised and Nones if not. If __exit__ returns a true value the exception is swallowed (step both cases in the explorer of section 1, group "with"). It is try/finally packaged as an object, for anything that must be released: files, locks, connections, GPU memory pools, timers, temporary settings such as torch.no_grad().
contextlib.contextmanager writes the class for you from a generator: the code before yield is __enter__, the code after it (in a finally) is __exit__. Several managers in one with are entered left to right and exited right to left. ExitStack handles a number of resources known only at run time (contextlib).
Timer exit: exc_type=None 1.0 ms open a open b body A B close b close a KeyError reached the caller open x open y open z using ['X', 'Y', 'Z'] close z close y close x suppressed
import contextlib, time class Timer: def __enter__(self): self.t0 = time.perf_counter() return self # bound to the name after `as` def __exit__(self, exc_type, exc, tb): self.ms = (time.perf_counter() - self.t0) * 1000 print(f"Timer exit: exc_type={exc_type.__name__ if exc_type else None}") return False # do not swallow exceptions with Timer() as t: sum(range(100_000)) print(f"{t.ms:.1f} ms") @contextlib.contextmanager # the same protocol, written as a generator def opened(name): print(f"open {name}") try: yield name.upper() # the value bound by `as` finally: print(f"close {name}") # runs even if the body raises try: with opened("a") as a, opened("b") as b: # entered left to right... print("body", a, b) raise KeyError("oops") except KeyError: print("KeyError reached the caller") # ...exited right to left with contextlib.ExitStack() as stack: # a number of resources known only at run time names = [stack.enter_context(opened(n)) for n in ("x", "y", "z")] print("using", names) with contextlib.suppress(FileNotFoundError): open("/no/such/file") print("suppressed")
The async form, async with, calls __aenter__ and __aexit__, which may await (opening a connection, releasing a semaphore); asyncio.timeout, TaskGroup and Semaphore use it, on Python: concurrency, asyncio and the GIL.
@contextmanager without try/finally around the yield. If the body raises, the exception is thrown in at the yield, and any cleanup written after it without finally never runs.Links checked 2026-10-05 (built 2026-10-26). Times for outside sources are rough reading times.
async with, TaskGroup and the exception groups it raises, on the event loop.Protocol types, which describe this page's protocols for a type checker.Sources and reproduction: src/pa/ holds every script shown on this page (code/), its recorded output (outputs/), run_all.sh to rerun them and versions.txt, copied from the Python essentials page's sources. Run on 2026-10-05 on an Apple M1 Pro, macOS 27, CPython 3.14.8 and 3.13.16.