Protocols in Python

Ian Kelly ian.g.kelly at gmail.com
Mon Aug 28 19:49:33 EDT 2017


On Mon, Aug 28, 2017 at 12:53 PM, Stefan Ram <ram at zedat.fu-berlin.de> wrote:
> ram at zedat.fu-berlin.de (Stefan Ram) writes:
>>The "The Python Library Reference, Release 3.6.0" (LIB) says:
>>»it must support the sequence protocol (the
>>__getitem__() method with integer arguments
>>starting at 0).«.
>>But in the "The Python Language Reference, Release 3.6.0"
>>(LANG) this is called »old sequence iteration« or »old-style
>>iteration« with the (new) sequence protocol being augmented
>>by »__len__«.
>
>   Can one say that the authoritative test for being »iterable«
>   and being »a sequence« is testing whether the object is an
>   instance of »collections.abc.Iterable« and
>   »collections.abc.Sequence«, respectively?

For Iterable, maybe. For Sequence, no.

Sequence doesn't define a __subclasshook__ method, perhaps for reasons
like your dict example. So the only subclasses of Sequence are those
that either explicitly have Sequence in their MRO or are registered
subclasses of Sequence: specifically, tuple, str, range, memoryview,
bytes, bytearray and list (plus their subclasses). There are probably
tons of legacy sequence types that aren't subclasses of Sequence.

>   Some parts of the references explain that implementing the
>   sequence protocol means to have a »__getitem__« method and
>   possibly also a »__len__« method. But, by inheritance,
>   »collections.abc.Sequence« seems to require /more/. I.e.,

As noted above, there is no minimum set of methods that will cause
Sequence to automatically consider something a subclass.



More information about the Python-list mailing list