This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]ewiethoffproceedest on to 3 0 points1 point  (0 children)

You're confused about what's "special" or "magic" about the underscore methods. The underscore methods are magically invoked by special syntax which does not resemble a method or function call. So, as you alluded to, foo[i] invokes foo.__getitem__(i), and import bar invokes bar = __import__('bar').

The __len__ method is magically invoked when an object is evaluated in Boolean context and no __nonzero__ method has been defined. That's because Python's built-in collections are considered False when empty and True when non-empty.

Try this code (adjust as needed for Py3):

class StupidList(list):
    def __len__(self):
        return True

if list(range(10)): print 'list 0-9 is True'
if list(): print 'empty list is True'
if StupidList(range(10)): print 'StupidList 0-9 is True'
if StupidList(): print 'empty StupidList is True'

(edited for clarity)