__call__ considered harmful or indispensable?
Diez B. Roggisch
deets at nospam.web.de
Thu Aug 2 15:23:05 EDT 2007
skip at pobox.com schrieb:
> 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?
Thanks to closures and bound methods, I don't think that there is a
case where you can't "fake" the missing __call__ at least when it comes
to call-backs. So in the end, you can always work around that. But if
you don't need to...
Se the gnosis multimethods for an implementation that makes sensible use
of the __call__-operator in my opinion.
diez
More information about the Python-list
mailing list