Search code examples
pythonbuilt-inmagic-methods

Are there redundant special methods on Python's built-in types?


In Fluent Python they say

You write len(my_object) and, if my_object is an instance of a user-defined class, then Python calls the __len__ instance method you implemented ...

But for built-in types like list, str, bytearray, and so on, the interpreter takes a shortcut: the CPython implementation of len() actually returns the value of the ob_size field in the PyVarObject C struct that represent the any variable-sized built-in object in memory.

But __len__ is still defined on at least some of these ...

>>> 'string'.__len__()
6
>>> [1, 2, 3].__len__()
3

What purpose do these methods serve if they're not called by len? And if are there other similar examples, what about them?


Solution

  • The fact that the CPython implementation doesn't call __len__() by default doesn't meant that there aren't any Python libraries or user programs out there which do. Keeping the method available is about API stability, even if CPython takes shortcuts where possible.