__call__ considered harmful or indispensable?

James Stroud jstroud at mbi.ucla.edu
Thu Aug 2 21:20:44 EDT 2007


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?


Consider this boring tedium:

def enclose(a, b):
   def _f():
     return do_something_with(a, b)
   return _f


And this is unbearable to look at:

def enclose(a, b):
   return lambda: do_something_with(a,b)


Which is related to this catastrophe:

in_the_midst_of_something(lambda a=a, b=b: do_something_with(a,b))


And this is just plain annoying:

import functools
def enclose(a, b):
   return functools.partial(do_something_with, a, b)


But __call__ allows for this pleasing little decorator for one's library:

import functools
class enclosable(object):
   def __init__(self, func):
     self.func = func
   def __call__(self, *args, **kwargs):
     return functools.partial(self.func, *args, **kwargs)

For example:

@enclosable
def do_something_with(a, b):
   [etc]


James


-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/



More information about the Python-list mailing list