__call__ considered harmful or indispensable?

Chris Mellon arkanes at gmail.com
Thu Aug 2 21:15:47 CEST 2007

On 8/2/07, Neil Cerutti <horpner at yahoo.com> wrote:
> On 2007-08-02, skip at pobox.com <skip at pobox.com> wrote:
> > 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?
> In C++ they are called functors, and they are very useful as
> surrogate functions with state. I haven't seen them used in the
> same way in Python much, because Python has more immediate
> solutions to (most of) these problems.

I don't think I've ever written one (in Python) except to demonstrate
how it worked. Pythons built in functions have all the functionality
that you'd have to use a functor for in C++.

More information about the Python-list mailing list