If you've ever tried assigning a __len__ method directly to a Python object instance—like my_obj.__len__ = lambda: 5—only to have len(my_obj) raise a TypeError, you're not alone. The mystery lies in how Python's len() function is implemented at the C level.
len() does not simply call obj.__len__(). Instead, it specifically looks for the __len__ method on the class of the object (via the type's tp_as_sequence slot). Moreover, Python requires a special internal type flag, Py_TPFLAGS_HAVE_LEN, to be set on the class for len() to work. Instance attributes are ignored entirely.
This design ensures consistency and performance: by enforcing class-level definition of dunder methods, Python guarantees that all instances of a class behave predictably. It also allows the interpreter to optimize len() calls without per-instance lookups.
Key takeaway: Always define __len__ on the class, not on individual instances. This is a classic example of Python internals that every developer should understand to avoid subtle bugs.
Day 19 of our Python under the hood series — follow for more CPython secrets.