Callable assertion?

Roy Smith roy at panix.com
Sun Oct 5 18:12:33 EDT 2003


"Terry Reedy" <tjreedy at udel.edu> wrote:
>> 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 :-)
 
> But it is the Python way.  Someone recently asked how to test if one
> can connect to a site without actually connecting and Alex M. gave
> much the same answer I did.  The frequent question "how can I tell if
> I can read a file without actually reading it" gets the stock answer
> 'you can't, not for sure', just as iscallable is 'not for sure'.

I hear what you're saying, but it's still nice to be able to check ahead 
of time.  What you're saying is analagous to "Why bother checking the 
safety because even if it's on now, by the time your finger slips and 
touches the trigger, it might not be on any more".

Let's say I write this:

class eventThingie:
   def __init__ (self, callback):
      self.callback = callback

   def go (self):
      if magic stuff happens:
         self.callback()

and then do:

myThingie = eventThingie (42)
myThingie.go()

When the magic stuff happens, I'll get a TypeError burried at the bottom 
of a stack trace, and none of the lines in the stack trace will be where 
my real error is.  On the other hand, if I add "assert callable 
(callback)" to my __init__() method, it'll be a lot easier to figure out 
what went wrong because the stack trace will happen right when and where 
the erroneous code is executed.  It's just like trying to track down 
pointer botches in C; by the time you get a segfault, you're nowhere 
near the cause of the problem.

It's a tradeoff.  By checking early, you give up a little flexibility 
and theoretical purity, but what you get back is better testability.

> Sorry, time-varying reality and the possibility of lies sometimes
> bites

If by "time-varying reality" you mean the dynamic nature of the 
language, that's an interesting problem.  It is certainly possible in 
theory that I could pass in an object which has no __call__() method, so 
callable() would return False, but also guarantee that by the time the 
object is actually called, I've managed to add a __call__() method to 
the object.  Theoretically possible, but diabolical, and not the kind of 
thing I'm going to worry about.




More information about the Python-list mailing list