[Tutor] Calling instance method in IDLE magically calls __len__?

Dino Bektešević ljetibo at gmail.com
Fri Sep 18 09:10:00 CEST 2015


Hello,

For full disclosure, I'm using Python2.7 on Ubuntu 14.04. MWE bellow and at
https://bpaste.net/show/3d38c96ec938 (until 2015-09-25 06:29:54, in the
case spaces get messed up).

class Errors:
    def __init__(self):
        pass
    def toFile(self):
        pass
    def __len__(self):
        print "len is called"
        return 0

Which is just fine if I call it over terminal, however calling it in IDLE:

>>> e = Errors()
>>> len(e)
len is called
0

as expected, but when try to call the method toFile, "len is called" gets
printed as soon as I put parenthesis "(" behind the toFile.

>>> len is called
e.toFile(

Now I recognize that I shouldn't use __len__ to print stuff, I should use
__string__ or at least __repr__, but I found it weird that __len__ would
get called in that situation. So out of a stupid mistake an interesting
question!

Why does the "len is called" get printed to IDLE when you try to call
toFile? How does the interpreter handle this? Any kind of clarification
would be greatly appreciated.

Hopefully I managed to get the right mailing list,
Dino


More information about the Tutor mailing list