Module 1: Runtime Model and the Data Model
The Python Data Model and Protocols
The Python Data Model and Protocols
The data model explains how user-defined objects participate in built-in syntax. Special methods implement behavioral protocols for length, indexing, iteration, containment, truth, formatting, calls, arithmetic, and context management.
Module: Module 1: Runtime Model and the Data Model
Core mental model
This lesson is built around four connected ideas. Read them as a decision framework, then prove each one with the walkthrough.
- len(obj), iter(obj), and repr(obj) dispatch through special methods.
- Protocols let behavior matter more than a declared inheritance tree.
- Special-method lookup often happens on the type rather than one instance.
- Implement only operations that are semantically natural for the object.
Walkthrough
class Batch:
def __init__(self, records):
self._records = tuple(records)
def __len__(self):
return len(self._records)
def __iter__(self):
return iter(self._records)
def __contains__(self, record):
return record in self._records
def __bool__(self):
return bool(self._records)Batch now composes with len, for, in, and truth tests without inventing custom verbs. The tuple storage supports a stable read-only batch interface, although contained records may still be mutable.
Hands-on lab
Design a DomainCollection that supports exactly four natural Python operations. Write tests against the built-ins rather than calling dunder methods directly, and explain one operation you intentionally excluded.
What to watch for
- Calling obj.__len__ directly bypasses the normal public built-in interface.
- Operator overloading that surprises readers makes an API less Pythonic.
- Implementing sequence behavior for a non-sequence creates misleading semantics.
Engineering checklist
- Connect the lesson's mental model to the choices made in the walkthrough.
- Test the normal case, an empty or boundary case, and one invalid case.
- Keep external input, side effects, and reusable logic in clearly separated layers.
- Prefer the clearest correct implementation before optimizing or generalizing it.
Completion check
You can implement the lab without copying the example, explain the core concepts in your own words, and show tests or terminal output that demonstrate the expected and failure paths.