Is 'isinstance()' the right thing?

Ralf Juengling juenglin at informatik.uni-freiburg.de
Tue May 28 09:00:19 EDT 2002


Alex Martelli <aleax at aleax.it> wrote in message news:<uttC8.40554$zW3.440516 at news1.tin.it>...
> Ralf Juengling wrote:
>         ...

> <sigh>.  So far I think I managed to explain it well enough to get the
> BDFL to agree this would be good IF Python had 'interfaces' as a concept
> separate from types and classes, so that 'requiredProtocol' would have
> to be an 'interface'.  I just can't manage to explain why types or
> classes would be just as good in the 'requiredProtocol' role as would
> be 'interfaces', so there's no need to wait for the latter and 246
> could just be allowed to go ahead now.  Oh well... one day I'll get some
> inspiration for how to go about it...

I must admit, I don't know the precise definition of an 'interface' 
nor that of a 'protocol' (are there widely accepted ones?).

My idea of a protocol is that of a 'set of functions or methods' 
which are to be used in a certain way (the functions signatures) for 
a certain purpose (what the functions do). The specification of the 
latter is done by the inventor of protocol.

Until recently, I used 'interface' and 'protocol' synonymic, but just 
realized that 'interfaces' seem to be a more general concept, comparable
to classes. (One can inherit from an existing interface and modify it 
and so on.)

In the rest, I focus on 'protocols' as roughly defined above. What I 
still do not understand:
Why aren't types not the right machinery for specifying the support 
of a protocol? Whenever someone introduces a new protocol, he would 
set up a new abstract type (or class), say (to become more Python related 
at the end)

class _iterator_:
    """This is an abstract class defining the iterator protocol
    """
    def __iter__(self): raise NotImplementedError
    def next(self): raise NotImplementedError

for the iterator protocol. Any class implementing the iterator 
protocol would be a subclass of '_iterator_' (probably among others) 
to signal, it is implementing this protocol.
To make sure, that an argument of my function is indeed an iterator, 

assert isinstance(arg, _iterator_) 

would be sufficient then.
Since we have multiple inheritance, it would not be a big deal to 
support this kind of type-based protocol checking. 
So, why isn't it there?

Regards,
Ralf



More information about the Python-list mailing list