Reputation: 7877
In Fluent Python they say
You write
len(my_object)
and, ifmy_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 oflen()
actually returns the value of theob_size
field in thePyVarObject
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?
Upvotes: 4
Views: 74
Reputation: 3675
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.
Upvotes: 1