Lesson · Python Data Model & Special Methods
Container Protocol Methods
55 min readContainer Protocol Methods
Special methods such as `__len__`, `__getitem__`, and `__iter__` let user-defined types participate in Python's normal container syntax. Protocol conformance often matters more than inheritance.
Learning goals
- Explain what each container operation calls:
len(bag)uses__len__,bag[1]uses__getitem__,"c" in baguses__contains__. - Implement those three methods on a custom class so
len, indexing, andinwork on it. - Explain how
__getitem__supports slices by receiving asliceobject and forwarding it to the underlying list. - Predict how iteration and membership change when a class defines
__getitem__but not__iter__or__contains__. - Add
__setitem__and__iter__and say which syntax form each one unlocks.
Mental model
The container protocols are rewrites: each piece of syntax calls one method, and the Bag example implements three of them so ordinary operators work on a custom type. The fallbacks are the important part: membership and iteration degrade to repeated indexing when the dedicated method is missing, which is why a class with only __getitem__ already supports a for loop.
Mental model
read it top to bottom
len(bag) → __len__ bag[1] → __getitem__(1) bag[0:2] → __getitem__(slice(0, 2)) bag[1] = "x" → __setitem__(1, "x") "c" in bag → __contains__, else __iter__, else __getitem__ for item in bag → __iter__, else __getitem__ with 0, 1, 2 ...
Core idea
The container protocols are the contract behind everyday syntax: len, indexing, assignment, membership, and iteration each delegate to a dunder method, and a class joins the club by implementing the methods it wants to support. The worked example's Bag delegates every call to its internal list, so len(bag), bag[1], and "c" in bag behave like list operations without the class being a list. The protocols also degrade gracefully: iteration and membership fall back to repeated __getitem__ calls when the dedicated methods are missing.
__len__
__len__ answers len(obj) and must return a non-negative integer; a negative result raises ValueError, and without __bool__ it also decides the object's truthiness, so empty length means falsy. Bag.__len__ forwards to the internal list, which keeps len(bag) matched to the items actually stored.
__getitem__
__getitem__ answers obj[key]: it receives the key, including a slice object for bag[0:2], and returns the element or raises IndexError (or KeyError for mapping-style keys). Bag.__getitem__ forwards straight to self._items[index], which is what makes negative indexes and slices work without extra code. A class with __getitem__ but no __iter__ can still be looped over: Python calls it with 0, 1, 2 until IndexError stops the loop.
__setitem__
__setitem__ answers obj[key] = value and is expected to mutate the container in place rather than return a value. Bag does not implement it in the worked example, so bag[1] = "x" raises TypeError; adding it means forwarding self._items[key] = value, and slice assignment arrives as a slice key just like in __getitem__.
__contains__
__contains__ answers item in obj and should return a truthy or falsy result; not in is derived as its negation. Bag.__contains__ delegates to the internal list, so "c" in bag uses list membership. When the method is missing, Python falls back to __iter__, or to repeated __getitem__ calls, which scans elements instead of using whatever membership logic the class could provide.
__iter__
__iter__ answers iter(obj): it should return an iterator object, and for loops, comprehensions, and unpacking all go through it. The worked example's Bag does not define it, so those features fall back to __getitem__ called with 0, 1, 2 until IndexError. Defining __iter__ as return iter(self._items) removes the fallback and states the intent directly.
Slicing support
Slice syntax bag[0:2] reaches __getitem__ as a single slice(start, stop, step) argument rather than a special method call. If __getitem__ forwards that object to a list, as Bag does, slicing, steps, and negative bounds all work for free; a hand-written implementation has to handle the slice case explicitly. __setitem__ receives the same slice objects for slice assignment.
Walkthrough
Bag.__init__copies whatever iterable it receives into a real list withlist(items), so the wrapper never shares storage with the caller's sequence.__len__returnslen(self._items), which makeslen(bag)print3;__getitem__returnsself._items[index], sobag[1]printsband would also accept slices or negative indexes.__contains__returnsitem in self._items, so"c" in bagprintsTruethrough list membership.- Predict before running: the single line
3 b True, and what changes if__contains__is deleted (membership then falls back to repeating__getitem__).
Experiments to try
- Print
bag[0:2],bag[-1], andbag[::2]; explain why all three work even thoughBagnever mentions slices. - Delete
__contains__and rerun"c" in bag: it still finds the item through the fallback; explain which method serves the check now and why that costs more as the bag grows. - Add
__setitem__forwarding to the list, then runbag[0] = "z"before and after the change; explain why assignment needs its own method instead of reusing__getitem__. - Loop over the bag with
for item in bagbefore and after adding__iter__; explain which method serves each version and what stops the fallback loop.
Common mistakes
- Expecting
len(bag)to work from__getitem__or__iter__: length comes only from__len__, so the call raisesTypeErrorwithout it. - Returning a non-integer or negative number from
__len__: Python raisesTypeErrorfor the wrong type andValueErrorfor a negative size at the point oflen(). - Writing a hand-made
__getitem__that returnsNonepast the end or raises something other thanIndexError, which breaks the iteration fallback that depends onIndexErrorto stop. - Confusing reading with writing: a class can support
bag[1]without supportingbag[1] = value, because__getitem__and__setitem__are separate protocols, and the failure shows up asTypeErroronly on assignment.
Practice: Easy
- Run the worked example and record the printed triple; then print
bag[0:2]andbag[-1]and name the method that serves both. - Create an empty
Bag([])and printbool(empty)andlen(empty); explain how one method produces both results. - Try
bag[0] = "z"on the unmodified class, read theTypeError, and name the missing method.
Practice: Medium
- Add
__setitem__and__iter__toBag, both forwarding toself._items, then verify thatbag[0] = "z",list(bag), andbag[1:]behave like the operations on a list. - Delete
__getitem__and__contains__fromBagtemporarily; check which offor,in, andlenstill work and connect each answer to the method that provides it or the fallback that rescues it. - Wrap a dict in a
Lookupclass with__getitem__,__contains__, and__len__overself._data; compare the error a missing key raises with the errorBag[99]raises and name both exception types.
Practice: Hard
- Build a
DaySetcontainer over an internal list that implements__len__,__getitem__,__iter__, and__contains__; write assertions proving each syntax form gives the same result as the underlying list. - Build a failure lab with three reproductions:
__len__returning a negative number and theValueErrorit triggers; a hand-written__getitem__that raisesKeyErrorpast the end and the brokenforloop it produces; a__getitem__that returnsNoneinstead of raising, and the runaway loop that follows. Explain each mechanism and its fix. - Connect this lesson to iteration: explain in order how
for x in objpicks__iter__when it exists and otherwise degrades to__getitem__with 0, 1, 2 ..., usingfor item in bagbefore and after adding__iter__as the demonstration.
Lesson checklist
- I can name the method behind
len(bag),bag[1],bag[0:2],"c" in bag, andfor item in bag. - I can implement
__len__,__getitem__, and__contains__on a class that wraps an internal list. - I can explain how the
__getitem__fallback powers iteration and membership when the dedicated methods are missing. - I can add
__setitem__and__iter__and say which syntax form each one unlocks.
Remember
Container protocols map syntax to methods: `len` goes to `__len__`, subscripting (including slices) to `__getitem__`, assignment to `__setitem__`, membership to `__contains__`, and loops to `__iter__`. The worked example's `Bag` implements three of them by forwarding to its internal list, and the two it skips still work for iteration and membership through the `__getitem__` fallback, at a scan cost that grows with the container.
Interview angles
What is the main purpose of **__len__**?+
__len__ answers len(obj) and must return a non-negative integer; without __bool__ it also decides truthiness, which is why bool(Bag([])) is false. Bag.__len__ forwards to the internal list so the reported size always matches the stored items.
What should you pay attention to when using **__getitem__**?+
__getitem__ answers obj[key] and receives a slice object for slice syntax; it returns the element or raises IndexError. Bag.__getitem__ forwards to self._items, which is why negative indexes and slices work without extra code, and why a for loop can fall back to it when __iter__ is missing.
How does **__setitem__** fit into this lesson?+
__setitem__ answers obj[key] = value and mutates the container in place. Bag does not define it in the worked example, so assignment raises TypeError; forwarding to self._items[key] = value fixes that, including slice assignment, which arrives as a slice key.
Why must a hand-written `__getitem__` raise `IndexError` (rather than return `None`) to support a `for` loop?+
When __iter__ is missing, for loops call __getitem__ with increasing indexes and stop only when IndexError is raised. Returning None or raising a different exception keeps the loop going forever or crashes it; IndexError is the signal that ends iteration.