__call__ considered harmful or indispensable?

Terry Reedy tjreedy at udel.edu
Fri Aug 3 14:49:49 EDT 2007


Skip Montanaro a écrit :
>>> 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
>     ...
>     if some_other_rare_condition_met:
>         ... several lines ...
>         obj = some.other_class()

Should that have been some.other_class (without the ()s?).  It is in the 
nature of Python's dynamic typing that mis-typing errors sometimes show up 
later than one would wish.  Hence the need for unit testing.  Consider

i = condition and 1 or '2' # whoops, should have been 2, without the 's
...
k = j * i # j an int; whoops, bad i value passes silently
...
use of k as string raises exception

I do not think __call__ should be specifically blamed for this general 
downside of Python's design.

Terry Jan Reedy






More information about the Python-list mailing list