[Python-3000] callable()

Nick Coghlan ncoghlan at gmail.com
Fri Jul 28 16:35:46 CEST 2006


Andrew Koenig wrote:
> I note in PEP 3000 the proposal to remove callable(), with the comment "just
> call the object and catch the exception."
> 
> I think that's a bad idea, because it takes away the ability to separate the
> callability test from the first call.  As a simple example, suppose you're
> writing a function that you expect to be given a function as one of its
> arguments:
> 
> 	def foo(bar, fun):
> 		assert callable(fun)
> 		# ...
> 
> It might be that foo doesn't actually call fun until much later.
> Nevertheless, from a testing viewpoint, it would be better to detect the
> error immediately of passing something that can't be called.
> 
> If you didn't have callable, how would you write this example?

How about changing callable's semantics to something like the following?:

   def callable(obj, attr="__call__"):
       if attr != "__call__":
           obj = getattr(obj, attr, None)
       return getattr(obj, "__call__", None) is not None


Test for callability:

   assert callable(obj)

Test for hashability:

   assert callable(obj, "__hash__")

Test for iterability:

   assert callable(obj, "__iter__")

Test for a context manager:

   assert callable(obj, "__enter__") and callable(obj, "__exit__")

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://www.boredomandlaziness.org


More information about the Python-3000 mailing list