Implement Container Protocols
Core idea
A container can support x[key] through __getitem__, key in x through __contains__, and len(x) through __len__. Sequence-style indexing uses integer positions and can accept slice objects; mappings usually use keys. Membership uses contains if available, then iteration, then old-style sequence indexing starting at zero. The sequence fallback ends when IndexError is raised. An iterator is an object that delivers successive values; iter() obtains one (covered in depth later).
class Readings: def __init__(self, values): self.values = list(values) def __getitem__(self, key): return self.values[key] def __len__(self): return len(self.values)r = Readings([4, 8, 12])print(r[-1], r[:2], len(r))The list handles negative indices and slices; the slice returns a list.
Define membership
class Approved: def __init__(self, codes): self.codes = set(codes) def __contains__(self, code): return code in self.codesa = Approved(["A", "B"])print("A" in a, "C" in a)The membership operation delegates to the underlying set.
Sequence fallback
class Batch: def __getitem__(self, index): return [5, 9][index]b = Batch()print(9 in b, 7 in b)print(list(b))IndexError from the backing list ends sequence-style traversal.
Common mistake
For missing mapping keys use KeyError; for invalid sequence positions use IndexError. Returning None for every out-of-range index can prevent sequence traversal from terminating.
Practice
Add iter to Readings returning iter(self.values), then test list(r), membership and an invalid index.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Container protocols
Check your understanding of container protocols.
What is printed?
class Batch: def __getitem__(self, i): return [4, 8][i]print(Batch()[-1])What is printed?
class Codes: def __contains__(self, key): return key == "X"c = Codes()print("X" in c, "Y" in c)What is printed?
class Batch: def __getitem__(self, i): return [2, 6][i]print(list(Batch()))Which exception ends old-style sequence indexing during iteration?