__call__ considered harmful or indispensable?

skip at pobox.com skip at pobox.com
Thu Aug 2 14:30:00 EDT 2007


I don't personally use __call__ methods in my classes, but I have
encountered it every now and then here at work in code written by other
people.  The other day I replaced __call__ with a more obvious method name,
so now instead of executing

    obj(foo, bar, baz)

the code in question is

    obj.execute(foo, bar, baz)

In this case there was a bug.  Depending on inputs, sometimes obj
initialized to a class, sometimes an instance of that class.  (I fixed that
too while I was at it.)  The problem was that the use of __call__ obscured
the underlying bug by making the instance as well as the class callable.

In this particular case it was clearly unnecessary and just obfuscated the
code.  I'm wondering, are there some general cases where __call__ methods of
a user-defined class are simply indispensable?

Thx,

Skip




More information about the Python-list mailing list