Skip to content

Lesson 3 of 9 · 24m

Python's Object Model: Dunder Protocols

How len, iteration, context managers, equality, and attribute access really work — and how to implement just enough of the object model without creating a puzzle box.

Python's object system is powerful because objects participate in protocols. len(x) is not a built-in special case; it asks for x.__len__(). with resource: calls __enter__ and __exit__. Iteration asks for __iter__. The mistake is thinking this means you should overload everything. A good object implements exactly the protocol its abstraction honestly supports.

Implement protocols that are true

class Window:
    def __init__(self, size: int):
        self.size = size
        self.items = []

    def push(self, item) -> None:
        self.items.append(item)
        del self.items[:-self.size]

    def __len__(self) -> int:
        return len(self.items)

    def __iter__(self):
        return iter(self.items)

Now len(window), for item in window, and list(window) work because the object really is a finite-sized iterable container. That is different from making len(user) mean 'number of permissions' because it felt clever. Cleverness at the protocol layer becomes a maintenance incident.

Equality and hashing are coupled

If two objects compare equal, they must have equal hashes. Python enforces this by removing __hash__ when you define __eq__ in a mutable class. That is not bureaucracy; it prevents objects from disappearing inside sets when their fields mutate. Frozen dataclasses handle the common case because value equality and immutable hash inputs are aligned.

Context managers are for guaranteed cleanup

class Transaction:
    def __init__(self, conn):
        self.conn = conn

    def __enter__(self):
        self.tx = self.conn.begin()
        return self.tx

    def __exit__(self, exc_type, exc, tb):
        if exc_type is None:
            self.tx.commit()
        else:
            self.tx.rollback()
        return False

Returning False means exceptions propagate. Swallowing exceptions by returning True is occasionally correct, but it is a loaded weapon. If a maintenance developer cannot tell whether errors escape your with block, the abstraction is lying.

Attribute hooks are last resorts

__getattr__, __setattr__, and __getattribute__ can implement lazy loading or proxies. They also make IDE navigation useless, break assumptions in inspect tools, and hide infinite recursion behind innocent-looking attribute access. Use __getattr__ for a narrow fallback, never as the primary interface. Properties are usually enough when you need computed attributes.

Field notes

  • repr should be unambiguous and debuggable: Money(cents=499, currency='USD'), not a marketing string.
  • Implement __len__ only if it is cheap and stable; expensive or network-backed lengths mislead callers.
  • Prefer returning iterators over exposing mutable internal collections.
  • If subclassing built-ins like list or dict, expect surprising interactions; composition is usually cleaner.

Was this lesson helpful?

Sign in to rate