__call__ considered harmful or indispensable?
skip at pobox.com
Fri Aug 3 04:39:23 CEST 2007
> > 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.
> I don't quite get the point here. A concrete example would be welcome.
The bug went something like this:
obj = some.default_class
... several lines ...
obj = some.other_class()
x = obj()
The bug was that in the rare condition branch obj should have been assigned
just the class. It shouldn't have been instantiated there. Having the
instance be callable (for no obvious reason that I could tell) misdirected
my attention because the x = obj() generally succeeded and I thought the
problem was with the call to x(...). If the instance wasn't callable it
would have been clear at "x = obj()" that I was trying to call an instance.
Thanks for the various bits of feedback. From the responses I've seen, it
seems that if one is tempted to use __call__ they should consider it before
just sprinkling it in their code. The places where people seem to use it
generally seem not to be in run-of-the-mill code. In the common case it
seems to me there are generally better ways to do things. (I did like the
StoredProcedure mirroring stuff someone posted. That does look kind of
More information about the Python-list