callable() builtin-function

Peter Hansen peter at engcorp.com
Wed Feb 19 19:09:37 EST 2003


Andrew Bennetts wrote:
> 
> On Wed, Feb 19, 2003 at 03:53:25PM +0100, Gerrit Holl wrote:
> > Hi,
> >
> > In the Python regrets list, at http://www.python.org/doc/essays/ppt/,
> > Although I can understand most of the regrets put there, I do not
> > understand why Guido has put the callable() function there, with the
> > comment "just call it".  AFAIK, callable(x) equals hasattr(x,
> > '__call__'), but what is wrong with callable()? Why could it be
> > something to regret? Can it be heavily abused? Is it ugly? Is it bad
> > style?
> 
> I suspect it's because it encourages code like:
> 
>     if callable(foo):
>         x = foo()
>     else:
>         x = foo
> 
> When it's probably more Pythonic to do:
> 
>     try:
>         x = foo()
>     except TypeError:
>         x = foo
> 

Of course, there is one potential problem with this, although the
fix for it is not necessarily callable().  The problem is if
the routine foo() really exists and is callable, but somewhere
inside has a failure which raises a TypeError.  This might
then be interpreted incorrectly.

It's not a trivial problem, but callable() does little more than
static type checking does in other languages.  It won't help avoid
the real bugs that might occur.

-Peter




More information about the Python-list mailing list