Data Model

Container Protocols

Container methods connect objects to indexing, membership, and item assignment.

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}
Container syntax routes to narrow protocol methods: assignment to __setitem__, membership to __contains__, lookup to __getitem__.

__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

98

Notes

See also

Run the complete example

Example code

Expected output

True
98

Execution time appears here after you run the example.