Python: the data model and protocols

How Python turns syntax into method calls on your types: operators and equality, copying and argument passing, iterators and generators, closures and decorators, the MRO, dataclasses, slots and descriptors, exceptions and context managers. Every example was run on CPython 3.14.8 (and 3.13.16 where the versions differ) on an Apple M1 Pro; the boxes under the code are the real outputs. A child of Python: the essentials. Data as of October 2026. Reading: 28 min, plus 21 in closed details.

The idea in one screen

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.

  1. Five stacks. 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.
  2. 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).
  3. 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.
  4. 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).
  5. 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.
  6. 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.

Special method
a double-underscore ("dunder") method such as __add__ that syntax calls for you.
Protocol
a set of special methods that makes an object usable somewhere (iteration, with, +); no base class needed.
NotImplemented
the value an operator method returns to say "not my type; ask the other operand".
Closure, cell
a function that keeps variables of the function that made it, stored in cells.
MRO
method resolution order: the list of classes that attribute lookup and super() walk.
Descriptor
a class attribute with __get__ (data descriptor: also __set__) that runs on attribute access; property, methods and slots are descriptors.
Exception group
one exception carrying several, handled with except*.

1. Syntax becomes method calls on the type

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 writePython callsFallback 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 + ba.__add__(b)if it returns NotImplemented: b.__radd__(a), then TypeError
a += ba.__iadd__(b)a = a + b
a == ba.__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.attrtype(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.

d1_vec.py
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)
real output, Python 3.14.8
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 NotImplementedError
Returning the singleton NotImplemented 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.

Three rules people learn the hard way

  • Special methods are looked up on the type, not the instance. "Implicit invocations of special methods are only guaranteed to work correctly if defined on an object's type, not in the object's instance dictionary" (Special method lookup). Setting x.__len__ = ... on one object does nothing for len(x). This lets CPython skip the instance dict on every operator.
  • A subclass on the right goes first. "If the operands are of different types, and the right operand's type is a direct or indirect subclass of the left operand's type, the reflected method of the right operand has priority" (same page). So a subclass can override how it combines with its parent from either side.
  • __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__.

== without __eq__
class P:
    def __init__(self, x): self.x = x
print(P(1) == P(1), len({P(1), P(1)}))
Predict the output, then reveal
real output, Python 3.14.8 (outputs/q_drills.json)
False 2
__eq__ without __hash__
class P:
    def __init__(self, x): self.x = x
    def __eq__(self, o): return self.x == o.x
print({P(1)})
Predict the output, then reveal
real output, Python 3.14.8 (outputs/q_drills.json)
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.

Fig. 2 · The methods Python called, in order, as the real run logged them

    Green rows logged themselves in a real run of code/d2_dispatch.py (CPython 3.14.8); grey rows happen inside C, where nothing can log; blue is the result, orange an exception.

    Data model explorer: which method does Python call, in what order?

    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.

      The full script that produced every trace (d2_dispatch.py)
      d2_dispatch.py
      """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()
      Three more predictions on truth, comparison and equal keys (recorded drills)
      bool of containers
      print(bool([]), bool([0]), bool(''), bool(' '), bool(0.0), bool(None))
      Predict the output, then reveal
      real output, Python 3.14.8 (outputs/q_drills.json)
      False True False True False False
      Chained comparison
      print(1 < 2 < 3, 3 > 2 > 1 == 1, (1 < 2) < 3, 1 == 1.0 == True)
      Predict the output, then reveal
      real output, Python 3.14.8 (outputs/q_drills.json)
      True True True True
      Dict keys that are equal
      d = {1: 'int', 1.0: 'float', True: 'bool'}
      print(d)
      Predict the output, then reveal
      real output, Python 3.14.8 (outputs/q_drills.json)
      {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.

      Costs and habits (what it solves, what it costs, when not to)
      What it solves
      Your types plug into every built-in, library and syntax form: sorted, sum, dict, f-strings, with, PyTorch's __torch_function__, NumPy's __array__.
      What it costs
      Every operator is a method lookup and call; that is a large part of why pure-Python arithmetic is slow (Python: CPython internals and performance).
      When not to
      Do not overload operators with surprising meanings; + should combine, == should compare. Prefer a dataclass (section 5) when you only need __init__, __repr__ and __eq__.

      2. Copies and calls: what a function receives

      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.

      Shallow and deep copies

      Fig. 3 · The shallow copy shares the inner list; the deep copy shares nothing with the original

      Recorded by 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.

      1. One list, one name. row = [1, 2]: one list object, L1, and the name row pointing at it.
      2. Two slots, one list. 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).
      3. The shallow copy. copy1 = grid.copy(): a new outer list L3, but its slots point at the same L1. A shallow copy copies one level.
      4. Mutating the inner list. grid[0].append(3) mutates L1, and every path to L1 sees it: row, both slots of grid and both slots of copy1.
      5. Changing the outer list. grid.append([9]) changes only the outer list L2. L3 is a different outer list, so copy1 still has two slots.
      real output of n3_copy.py, Python 3.14.8
      9 0
      [[1, 0], [1, 0], [1, 0]]
      [[1, 0], [0, 0], [0, 0]]
      The code (n3_copy.py)
      n3_copy.py
      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)
      Multiplying a nested list
      grid = [[]] * 3
      grid[0].append('x')
      print(grid)
      Predict the output, then reveal
      real output, Python 3.14.8 (outputs/q_drills.json)
      [['x'], ['x'], ['x']]
      The [[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.

      Passing arguments: the function gets the object, not a copy

      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.

      n4_args.py
      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))
      Predict the output, then reveal
      real output, Python 3.14.8
      ['a', 'new']
      [1, 2] [1, 2]
      [1] [2]

      += is a method call too

      a += 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:

      += on a tuple vs a list
      a = (1, 2)
      b = a
      a += (3,)
      print(a, b)
      Predict the output, then reveal
      real output, Python 3.14.8 (outputs/q_drills.json)
      (1, 2, 3) (1, 2)
      n5_tuple.py
      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)
      Predict the output, then reveal
      real output, Python 3.14.8
      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 same file under Python 3.13 (the unhashable-key message changed in 3.14)

      The dict-key error message is new in 3.14 (What's new in 3.14); 3.13 said only "unhashable type: 'list'":

      the same file, real output, Python 3.13.16
      TypeError: 'tuple' object does not support item assignment
      ([1, 3], 2)
      TypeError: unhashable type: 'list'
      {(1, 2): 'x'}
      One more prediction: changing a list while looping over it (n6_iter_mutate.py)
      n6_iter_mutate.py
      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)
      Predict the output, then reveal
      real output, Python 3.14.8
      [1, 2, 3]
      [1, 3]
      RuntimeError: dictionary changed size during iteration
      Costs and habits (what it solves, what it costs, when not to)
      What it solves
      No copying on assignment or call: passing a 10 GB list costs the same as passing an int.
      What it costs
      Spooky action at a distance: any alias can change what you hold.
      Habits
      Do not mutate arguments unless that is the function's job (and say so); return new objects; prefer tuples and frozen dataclasses for values that should not change.

      3. Iterators and generators: laziness as a protocol

      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).

      g1_protocol.py
      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
      Predict the output, then reveal
      real output, Python 3.14.8
      list_iterator 1 2 3
      StopIteration: the iterator is used up
      14 0
      6 6
      A generator used twice
      g = (x * 2 for x in range(3))
      print(list(g), list(g))
      Predict the output, then reveal
      real output, Python 3.14.8 (outputs/q_drills.json)
      [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.

      Lazy pipelines: one item at a time through every stage

      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

      1. read_list reads every line first. Printed read {"user": "a", read oops, read {"user": "b": all three lines go into one list before anything downstream starts. Held: 3 items.
      2. Then parse_list parses them all. Printed 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).
      3. Then count_list counts. Printed count a 2, count b 1; the read list is gone, the parsed one is still held. Held: 4 items (2 messages, 2 counts).
      4. sum adds the last list: total 3. Every stage ran to the end before the next began, so each intermediate list existed in full.

      "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.

      The program and its printed trace (g2_order.py)
      g2_order.py
      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)))))
      real output, Python 3.14.8
      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 3

      At 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.

      real output of g3_memory.py, Python 3.14.8
      eager  total=7000000  peak=108,190.2 KiB
      lazy   total=7000000  peak=      1.1 KiB
      The code (g3_memory.py)
      g3_memory.py
      """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.

      Streaming tokens like an LLM client

      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.

      real output of g5_stream.py, Python 3.14.8
      [open connection]
      [close connection]
      'Python generators stream lazily.'
      [open connection]
      consumer stopped
      [close connection]
      after close
      The code (g5_stream.py)
      g5_stream.py
      """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.

      g4_yield_from.py
      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)
      real output, Python 3.14.8
      [1, 2, 3, 4, 5]
      [60]
      itertools, the standard lazy toolkit, and two lazy built-ins (predictions)
      g6_itertools.py
      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))
      Predict the output, then reveal
      real output, Python 3.14.8
      [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.

      zip stops at the shortest
      print(list(zip('abc', [1, 2])))
      try:
          print(list(zip('abc', [1, 2], strict=True)))
      except ValueError as e:
          print('ValueError:', e)
      Predict the output, then reveal
      real output, Python 3.14.8 (outputs/q_drills.json)
      [('a', 1), ('b', 2)]
      ValueError: zip() argument 2 is shorter than argument 1
      map is lazy
      calls = []
      m = map(calls.append, [1, 2, 3])
      print(calls)
      list(m)
      print(calls)
      Predict the output, then reveal
      real output, Python 3.14.8 (outputs/q_drills.json)
      []
      [1, 2, 3]
      Costs and habits (what it solves, what it costs, when not to)
      What it solves
      Constant memory over unbounded input; work starts before the input ends; one stage per function.
      What it costs
      Single use (a consumed iterator is silently empty), harder debugging (nothing runs until something consumes), a little per-item overhead.
      When not to
      When you need the data twice, random access, or len: materialise a list once, deliberately.

      4. Functions, closures and decorators

      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.

      Closures: functions that remember variables

      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).

      f1_closure.py
      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)
      Predict the output, then reveal
      real output, Python 3.14.8
      1 2 3 3
      [2, 2, 2]
      [0, 1, 2]
      UnboundLocalError: cannot access local variable 'total' where it is not associated with a value
      Late binding
      fs = []
      for i in range(3):
          fs.append(lambda: i * 10)
      print([f() for f in fs])
      Predict the output, then reveal
      real output, Python 3.14.8 (outputs/q_drills.json)
      [20, 20, 20]
      Closure assignment
      x = 1
      def f():
          print(x)
          x = 2
      f()
      Predict the output, then reveal
      real output, Python 3.14.8 (outputs/q_drills.json)
      UnboundLocalError: cannot access local variable 'x' where it is not associated with a value

      Decorators

      @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").

      real output of f2_decorator.py, Python 3.14.8
      work took 0.040 s
      333332833333500000
      work Sum of squares. work
      wrapper None
      The code (f2_decorator.py)
      f2_decorator.py
      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__)
      Decorator order
      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())
      Predict the output, then reveal
      real output, Python 3.14.8 (outputs/q_drills.json)
      <b><i>hi</i></b>
      A decorator with arguments: a retry helper for a model API (f3_retry.py)

      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.

      f3_retry.py
      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)
      real output, Python 3.14.8
      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 request

      Backoff, 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.

      Caching with 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.

      real output of f4_cache.py, Python 3.14.8
      23416728348467685 calls: 81
      CacheInfo(hits=78, misses=81, maxsize=None, currsize=81)
      without the cache, fib(25) makes 242785 calls
      TypeError: unhashable type: 'list'
      The code (f4_cache.py)
      f4_cache.py
      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)
      Caching pitfalls
      Arguments become a dict key, so they must be hashable (the TypeError above, section 1's __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.
      Parameters: positional-only, keyword-only and the catch-alls (prediction)

      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.

      f5_params.py
      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))
      Predict the output, then reveal
      real output, Python 3.14.8
      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.

      Costs and habits (what it solves, what it costs, when not to)
      What it solves
      Cross-cutting behaviour (timing, retries, caching, auth, registration in a framework such as FastAPI's @app.get) written once.
      What it costs
      An extra call per invocation, and indirection when reading a stack trace.
      When not to
      When a plain function call at the call site would be clearer, or when the decorator changes the function's signature in ways type checkers cannot follow.

      5. Classes: the MRO, dataclasses, slots and descriptors

      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.

      Multiple inheritance and the MRO

      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).

      1. A diamond. 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.
      2. C3 turns the graph into one stack. The run printed 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.
      3. 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.
      4. The same class on its own: a shorter stack. 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.
      5. No consistent order, no class. 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.
      real output of c1_mro.py, Python 3.14.8
      ['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
      The code (c1_mro.py)
      c1_mro.py
      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)
      super() follows the MRO
      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())
      Predict the output, then reveal
      real output, Python 3.14.8 (outputs/q_drills.json)
      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.

      Dataclasses: classes for data, without the boilerplate

      @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).

      real output of c2_dataclass.py, Python 3.14.8
      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') False
      The code (c2_dataclass.py)
      c2_dataclass.py
      from 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.

      Fig. 6 · Slots cut a record from 96 to 56 bytes; a dict per record costs twice a plain object

      class96.1 B
      class + __slots__56.0 B
      dataclass96.0 B
      dataclass(slots=True)56.0 B
      namedtuple80.0 B
      tuple72.0 B
      dict192.0 B
      Bytes per record, from outputs/c3_sizes.txt (CPython 3.14.8, Python allocations only). The script is in the closed block below.
      The measuring script and its output (c3_sizes.py)
      c3_sizes.py
      """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")
      real output, Python 3.14.8
      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
      __slots__
      class S:
          __slots__ = ('x',)
      s = S()
      s.x = 1
      s.y = 2
      Predict the output, then reveal
      real output, Python 3.14.8 (outputs/q_drills.json)
      AttributeError: 'S' object has no attribute 'y' and no __dict__ for setting new attributes

      Descriptors: how property, methods and self work

      A 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.

      1. Four places, in a fixed order. For 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.
      2. 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.
      3. 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.
      4. 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.
      5. 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.
      6. A method is found on the class and bound. Now 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.
      7. Writes meet the data descriptors first. 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.

      real output of c4_descriptor.py, Python 3.14.8
      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 True
      The code (c4_descriptor.py)
      c4_descriptor.py
      class 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
      Why 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.

      c6_method_call.py
      import dis
      dis.dis("s.describe()")            # the direct call form: method and self pushed separately
      real output, Python 3.14.8
        0           RESUME                   0
      
        1           LOAD_NAME                0 (s)
                    LOAD_ATTR                3 (describe + NULL|self)
                    CALL                     0
                    RETURN_VALUE

      And 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.

      c5_classattr.py
      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)
      Predict the output, then reveal
      real output, Python 3.14.8
      ['search'] False
      ['calc'] ['search'] ['search']
      Class attribute vs instance attribute
      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)
      Predict the output, then reveal
      real output, Python 3.14.8 (outputs/q_drills.json)
      2 0 0
      Costs and habits (what it solves, what it costs, when not to)
      Choose
      A dataclass for plain records; a frozen dataclass for values and dict keys; Pydantic at trust boundaries; a Protocol (on the typing page) instead of a base class when you only need "has these methods".
      Avoid
      Inheritance for code reuse alone; metaclasses unless you are writing a framework (__init_subclass__ covers most "run code when a subclass is defined" needs); mutable class attributes.

      6. Exceptions: the hierarchy, chaining and groups

      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.

      The hierarchy, and what except Exception does not catch

      Everything 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":

      Catching Exception
      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')
      Predict the output, then reveal
      real output, Python 3.14.8 (outputs/q_drills.json)
      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.

      Fig. 8 · except Exception catches one branch; Ctrl-C, sys.exit(), GeneratorExit and cancellation sit outside it

      except Exceptioncatches this branchnot under Exception:they pass through itBaseExceptionExceptionLLMErrorRateLimitedContextTooLongKeyboardInterruptSystemExitGeneratorExitasyncio.CancelledErroryour library's root
      The four outside are named in the text; the issubclass answers and RateLimited.__mro__ are in the real output of e3_hierarchy.py below, whose classes form the blue branch.
      real output of e3_hierarchy.py, Python 3.14.8
      wait 1.5
      ContextTooLong 10000 tokens > 8192
      ['RateLimited', 'LLMError', 'Exception', 'BaseException', 'object']
      False True
      True
      False
      The code (e3_hierarchy.py)
      e3_hierarchy.py
      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))
      Correction to the old page
      The old page listed as a trap "Catching 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.

      Chaining: raise ... from

      Raising 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.

      Both tracebacks, real (e1_chain.py)
      e1_chain.py
      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
      real output, Python 3.14.8
      --- 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

      Exception groups, except* and notes

      Concurrent 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.

      real output of e2_group.py, Python 3.14.8
      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'"]
      The code (e2_group.py)
      e2_group.py
      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 finally

      e4_finally.py
      def 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())
      Predict the output, then reveal
      real output, Python 3.14.8
      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).

      The same file under 3.13, and two more predictions (finally, and else after a loop)

      Under 3.13 the same file prints no warning:

      the same file, real output, Python 3.13.16
      try
      else (only when try raised nothing)
      finally (always)
      try
      except
      finally (always)
      finally's return wins
      finally and return
      def f():
          try:
              return 'try'
          finally:
              print('finally runs first')
      print(f())
      Predict the output, then reveal
      real output, Python 3.14.8 (outputs/q_drills.json)
      finally runs first
      try
      else after a loop
      for n in [3, 5, 7]:
          if n % 2 == 0:
              print('found even'); break
      else:
          print('no break happened')
      Predict the output, then reveal
      real output, Python 3.14.8 (outputs/q_drills.json)
      no break happened

      A loop's else runs when the loop ended without break; it is the "not found" branch of a search.

      Costs and habits (what it solves, what it costs, when not to)
      Habits
      Catch the narrowest exception you can handle; let the rest propagate; translate at boundaries with raise ... from; log with the traceback (logger.exception) once, at the top.
      Mistakes
      Bare except:; except Exception: pass; catching around more code than the call that can fail; raising Exception("...") instead of a specific class.

      7. Context managers: with

      with 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).

      real output of x1_with.py, Python 3.14.8
      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
      The code (x1_with.py)
      x1_with.py
      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.

      The mistake
      Writing @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.