Skip to content

Python looks simple, and most of the time it is. Underneath the simplicity sits a data model that is unusually open: every operator, attribute lookup, iteration, and with block is a call to a dunder method you can define yourself. The exercises in this chapter go below the surface on purpose. They make you build the machinery that frameworks hide (descriptors behind an ORM, generators behind a pipeline, the event loop behind asyncio, the import system behind every import) so that the next time a library does something surprising, you know which hook it used.

Concepts from other sections (2)

This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.

The chapter is a set of exercise briefs rather than worked solutions. Several briefs are the same problem a section elsewhere in the books solves in full, and for those the brief links to that section so you can reason through your own design first and then compare it with a complete, tested one.

Learning objectives

  • Describe CPython’s memory model, Python’s gradual type system, its exception model, and the tradeoffs between asyncio, threads, and processes.
  • Use the data model (dunder methods, descriptors, context managers) to make your own types behave like built-ins.
  • Build lazy pipelines with generators and explain what send and throw add to plain iteration.
  • Reason through the design of each exercise before reading the matching worked solution elsewhere in the books.

You should be comfortable writing Python classes, functions, and tests, and running a project with uv. If you have not used asyncio before, read Python asyncio: event loop, tasks, cancellation, bounded concurrency in Programming and Algorithms before the scheduler brief.

CPython manages memory by reference counting, backed by a cycle-detecting garbage collector for structures that point at themselves. Everything is an object, including integers, functions, and classes, which is what makes the data model so uniform. __slots__ trades the per-instance __dict__ for a fixed layout when memory matters.

Typing is dynamic, with optional gradual static typing through the typing module: protocols for structural interfaces and TypeVar for generics. The interpreter ignores annotations; checkers such as mypy and pyright enforce them.

Errors are exceptions, handled with try, except, else, and finally. Since 3.11, ExceptionGroup lets concurrent code raise several failures at once. For concurrency you choose between asyncio for I/O-bound work on one thread, threading (serialized by the global interpreter lock for Python bytecode), multiprocessing for CPU-bound work, and, from 3.13, an experimental free-threaded build without the GIL. Projects are managed with uv or pip and pyproject.toml, and linted with ruff. The exercises target CPython 3.12 or later.

  • Dunder methods (__init__, __repr__, __iter__) so your types conform to Python’s protocols.
  • Generators and yield from for lazy sequences.
  • Decorators, on functions and classes, for cross-cutting concerns.
  • Context managers (the with statement, __enter__ and __exit__) for scoped resources.
  • Comprehensions (list, dict, set, generator) instead of explicit accumulation loops.
  • dataclasses and attrs for structured data.
  • Descriptors for controlling attribute access.
  • The match statement (3.10 and later) for structural pattern matching.

The briefs are listed below, ordered by concept rather than by difficulty, so choose by the difficulty rating (1 is easiest, 5 hardest) rather than by number. Worked Python solutions for these exercises have not been written yet; where a full solution of the same problem exists elsewhere in the books, the last column links to it.

#ExerciseConceptsDifficulty (1-5)Worked elsewhere
01Descriptor-based ORMDescriptors, metaclasses, __set_name__4
02Async task schedulerasyncio, event loop, Future, cancellation3Python asyncio; Async fetch with resume, checksums, and license capture
03Generator-based pipelineyield, send, throw, coroutine chaining3Extract, normalize, and quality filters
04Property-based test frameworkDecorators, inspect, random generation, shrinking4Property-based tests with Hypothesis, proptest, rapid, and ol_prop.h
05LRU cache with TTL__hash__, __eq__, doubly-linked list, threading.Lock3Response cache: LRU, TTL, singleflight, and tenant-scoped keys
06Import hook (custom loader)importlib, sys.meta_path, ModuleSpec5
07Dataclass code generatorast module, metaprogramming, exec4
08Actor model (multiprocessing)multiprocessing.Queue, Process, message passing3Near-duplicate dedup: MinHash, LSH, union-find, and decontamination
09Type checker (subset)typing, AST walking, unification algorithm5
10WSGI framework (mini-Flask)WSGI spec, decorators, routing, middleware3

The linked sections come from Programming and Algorithms, Data Engineering, Software Engineering, and AI Engineering, where each problem is solved as part of a larger system rather than in isolation.

  • Reference counting: memory management in which each object counts the references to it and is freed when the count drops to zero; CPython uses it, backed by a cycle-detecting garbage collector for objects that refer to each other.
  • Global interpreter lock (GIL): CPython’s lock that lets only one thread execute Python bytecode at a time, so threads speed up I/O-bound work but not CPU-bound work; an experimental free-threaded build from 3.13 removes it.
  • Gradual typing: a type system in which static type annotations are optional and unannotated code stays dynamically typed; Python’s interpreter ignores annotations, and checkers such as mypy and pyright enforce them.
  • Dunder method: a method named with double underscores, such as __iter__ or __eq__, that Python calls to carry out an operator, attribute lookup, iteration, or with block; defining them makes your types behave like built-ins.
  • Context manager: an object with __enter__ and __exit__ methods, used in a with statement, so the setup and cleanup of a scoped resource happen on every exit path, including exceptions.
  • Python documentation: the authoritative reference.
  • Data model reference: essential for every brief in this chapter.
  • Fluent Python by Luciano Ramalho, 2nd edition: deep Pythonic patterns.
  • Python Cookbook by Beazley and Jones: recipes.
  • Real Python: tutorials.