Data Model
Container Protocols
Container protocols let a class behave like the collection it represents. Instead of inventing method names such as has() or lookup(), the object can support in, indexing, and assignment.
The key methods are small and familiar: __contains__ powers in, __getitem__ powers obj[key], and __setitem__ powers obj[key] = value. Add only the operations the object can honestly support.
This keeps the public interface aligned with Python's built-in containers. Callers can use the same syntax for custom records, caches, tables, and sequence-like objects.
__setitem__ gives assignment syntax to a custom container.
Source
class Scores:
def __init__(self):
self._scores = {}
def __setitem__(self, name, score):
self._scores[name] = score
scores = Scores()
scores["Ada"] = 98
print(scores._scores)Output
{'Ada': 98}__contains__ answers membership tests written with in.
Source
class Scores:
def __init__(self):
self._scores = {"Ada": 98}
def __contains__(self, name):
return name in self._scores
scores = Scores()
print("Ada" in scores)Output
True__getitem__ connects bracket lookup to your internal storage.
Source
class Scores:
def __init__(self):
self._scores = {"Ada": 98}
def __getitem__(self, name):
return self._scores[name]
scores = Scores()
print(scores["Ada"])Output
98Notes
- Implement the narrowest container protocol your object needs.
- Use
KeyErrorandIndexErrorconsistently with built-in containers. - If a plain
dictorlistis enough, prefer it over a custom container.
See also
- prerequisite: Lists
- prerequisite: Dictionaries
- related: Special Methods
Run the complete example
Expected output
True
98
Execution time appears here after you run the example.