Callable assertion?

Peter Hansen peter at engcorp.com
Sun Oct 5 17:43:10 EDT 2003


Roy Smith wrote:
> 
> I want to test
> the paramater for correctness in my constructor, but I don't actually
> want it called until it's supposed to be called.  Calling the function
> to prove it's callable is kind of like checking to see if a gun's safety
> is on by pulling the trigger :-)

Okay, new scenario: we find a gun, and for some reason you are
willing to take my word for it that the safety is on, because
you intend to point it at your head and pull the trigger.

Which do you trust more: me looking at the safety and telling
you that it appears to be on, as I hand you the gun, or me
pulling the trigger and, if the gun doesn't fire, handing you
the gun? ...

The point is, that in the end, testing for callable only 
tests for the *appearance*, correct though it may be in many
or most cases.  No matter what, you can't prove that it can
be called until you try to call it.  And in that case you 
must still be prepared to handle the cases where the call fails,
or other situations.  

What if I give you an object which appears to be callable, so 
you stuff a reference somewhere in your constructor, because 
after all "it's safe to call".  Then, by the time you actually
try to call it, the object has morphed itself into something
without a __call__ method.  The attempt to call it will fail.

Same logic as checking that a file exists before you actually
try to use it: no guarantee it will still exist later, so save
the wasted effort and just be ready for the exception that will
be thrown when it turns out not to exist.

There are times when what you are trying to do is the right 
thing, maybe, probably, but it's rarely the case.  If you are
sure, then callable() is what you need.  Otherwise just catch
exceptions as appropriate.

-Peter




More information about the Python-list mailing list