[Python-3000] callable()

Stefan Behnel behnel_ml at gkec.informatik.tu-darmstadt.de
Fri Jul 28 07:04:42 CEST 2006



Steven Bethard wrote:
> On 7/27/06, Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:
>> Guido van Rossum wrote:
>>> So how about we change callable() and add hashable(), iterable() and
>>> whatever else makes sense so that these all become like this:
>>>
>>>   def callable(x):
>>>     return getattr(x, "__call__", None) is not None
>> This *still* doesn't fully solve the problem in the case
>> of __hash__, since a container may be unhashable due to
>> its contents, even if it has a __hash__ method itself.
> 
> For that matter, it doesn't solve the problem for __call__ or __iter__
> either since they could also raise TypeErrors.  Any of these
> method-checking approaches can only tell you if an object *doesn't*
> support operation X.

What they tell you is that the object supports the /protocol/. It does not
mean that everything from the protocol will succeed when you try. It does not
tell you about the /state/ of the object or its environment that might let the
operation fail (IOError etc.). In the case of iterable(), it does not tell you
that there is something to iterate over or that things like file-iteration
will not fail. In the case of callable(), it does not tell you what the
correct signature is or if the operation triggered by the call will succeed.
In the case of hashable(), it does not tell you that the entire thing
(including subtrees or whatever) is hashable in its current state at the time
of hashing.

It just says: I support the protocol, so it makes sense to apply the protocol
operations to me if you need to.

I think that's perfectly reasonable semantics for the three functions. So,
with the small enhancement above that allows setting the special methods to
None to deliberately /disable/ support for the protocol in an object (or
class), I think the semantics of the *able() functions are very clear and clean.

Stefan


More information about the Python-3000 mailing list