I'm reading a book on Python, and it says that when you make a call to help(obj)
to list all of the methods that can be called on obj
, the methods that are surrounded by __
on both sides are private helper methods that cannot be called.
However, one of the listed methods for a string is __len__
and you can verify that if s
is some string, entering s.__len__()
into Python returns the length of s
.
Why is okay to call some of these methods, such as __len__
, but others cannot be called?
The book is incorrect. You can call __dunder__
special methods directly; all that is special about them is their documented use in Python and how the language itself uses them.
Most code just should not call them directly and leave it to Python to call them. Use the len()
function rather than call the __len__
method on the object, for example, because len()
will validate the __len__
return value.
The language reserves all such names for its own use; see Reserved classes of identifiers in the reference documentation:
System-defined names, informally known as "dunder" names. These names are defined by the interpreter and its implementation (including the standard library). Current system names are discussed in the Special method names section and elsewhere. More will likely be defined in future versions of Python. Any use of
__*__
names, in any context, that does not follow explicitly documented use, is subject to breakage without warning.