[Python-3000] callable()

Michael Urman murman at gmail.com
Tue Jul 18 19:51:26 CEST 2006


On 7/18/06, Guido van Rossum <guido at python.org> wrote:
> But I'm not proposing to use hasattr(obj, '__call__'). I'm basically
> saying that the callable test has very little to do with whether the
> later call will succeed, because we have no way to test the signature.

Agreed. I think the people who want to use this as a test for whether
a client passed them a usable object are barking up the wrong tree.
What I do see it as useful for is making an api that accepts a
foo-like-object, or a callable object that returns a foo-like-object.
For properly defined scenarios this is perfectly well defined. One
such case may be for passing strings or string-yielders into a
templating system. If calculating the string is expensive, and it may
only be used conditionally, one may wrap the calculation as a deferred
callable.

On the other hand, that scenario is just as amenable to the try/except
handling, because if it can be called you do want to call it right
then.

The client-callback being passed as the wrong parameter scenario is
one that benefits from early checking. If you wait until you need to
call it, and it's not callable, the error message is more disorienting
than could be arranged by an early check. If it has the wrong
signature, passing the callable() check, but fails at call, the error
message is much more useful. If it raises another error inside the
function, there's a useful trace pointing to the raising code.

> > As for callable() vs addable(), etc., the reason is obvious. Function
> > calls very commonly have large side effects and are only rarely
> > idempotent. The operations you mention are expected to have no side
> > effects on the object. This makes a try/except much more palatable for
> > addition, subscripting, etc. than for calling a function.
>
> That's not at all obvious to me, and certainly I'm *not* proposing
> surrounding everything with a try/except.

Absolutely not. For both I think the error should generally just be
thrown. But when the error needs to be caught locally, it would be an
unusual case that the try/except would have side effects for addition.

> IMO the right solution lies in something like pychecker, not in adding
> look-before-you-leap type checks

I think this varies strongly on what scenario you are addressing. It's
hard to verify your own API against future users with a static tool
like pychecker.

Michael
-- 
Michael Urman  http://www.tortall.net/mu/blog


More information about the Python-3000 mailing list