Re:What's better about Ruby than Python? - comp.lang.python
by avibryant on Saturday August 28, 2010 @01:24AM
(#1641256)
I've been puzzled by len() and company for a long time and this is the most complete and sensible explanation I've heard. Thank you.
I still think it's the wrong design, mind you, but I no longer think it's a crazy one.
Example: If __len__ is defined on an object x, and __nonzero__ (Py2) or __bool__ (Py3) is not defined, then "not x" will test if x.__len__() == 0.
Similarly, __contains__ interacts with "foo in x", and __eq__ and __hash__ are expected to play well together for hashable objects (e.g. unique members of a set).
The double underscores are a useful code smell that indicates you're changing how an object interacts with Python's syntax.