Iterators and Generators
- The iterator protocol. A for loop calls iter() then next() until StopIteration: that protocol is all iteration is.
- Generators. A function with yield becomes a generator: it pauses at each yield and resumes exactly there on demand.
- Lazy pipelines. Generators are lazy: chaining them processes a million-line file with only one line in memory at a time.
Context Managers
- Writing one. A class with __enter__ and __exit__ is a context manager: files, locks and transactions all wear this shape.
- contextmanager decorator. The contextmanager decorator turns a generator into a context manager: setup, one yield, cleanup.
- When to reach for one. Any pattern of acquire-then-guaranteed-release: timers, temporary settings, connections: deserves a with block.
Decorators and Reusable Behaviour
- Decorators. A decorator is a function that takes a function and returns an enhanced one: @retry wraps without editing.
- functools.wraps. Use wraps inside a decorator so the wrapped function keeps its name and docstring for debugging.
- Standard decorators. The library ships useful ones: lru_cache memoises pure functions, property turns a method into an attribute.
Before and after this level
- Before: Level 8: Files & Data: Files and Paths, JSON, CSV and Serialisation, Resource Management.
- Next: Level 10: Types & Modern Python: Type Hints, Generics and Protocols, Static Type Checking.
In the app each of these ideas is taught and then asked back, and the level ends with a checkpoint and flashcards. See Checkpoints and flashcards.
Frequently asked questions
What does Python Level 9: Iteration & Pythonic Design cover?
Iterators and Generators, Context Managers, Decorators and Reusable Behaviour: 3 lessons and 9 ideas.
What should I know before this level?
The level before it, Level 8: Files & Data, which covers Files and Paths, JSON, CSV and Serialisation, Resource Management.