New submission from Martijn Pieters:

The collections.abc documentation implies that *any* of the container ABCs can 
be used in an issubclass test against a class that implements all abstract 
methods:

> These ABCs allow us to ask classes or instances if they provide particular 
> functionality [...]

In reality this only applies to the "One Trick Ponies" (term from PEP 3119, 
things like Container and Iterable, those classes with one or two methods). It 
fails for the compound container ABCs:

>>> from collections.abc import Sequence, Container, Sized
>>> class MySequence(object):
...     def __contains__(self, item): pass
...     def __len__(self): pass
...     def __iter__(self): pass
...     def __getitem__(self, index): pass
...     def __len__(self): pass
... 
>>> issubclass(MySequence, Container)
True
>>> issubclass(MySequence, Sized)
True
>>> issubclass(MySequence, Sequence)
False

That's because the One Trick Ponies implement a __subclasshook__ method that is 
locked to the specific class and returns NotImplemented for subclasses; for 
instance, the Iterable.__subclasshook__ implementation is:

    @classmethod
    def __subclasshook__(cls, C):
        if cls is Iterable:
            if any("__iter__" in B.__dict__ for B in C.__mro__):
                return True
        return NotImplemented

The compound container classes build on top of the One Trick Ponies, so the 
class test will fail, NotImplemented is returned and the normal ABC tests for 
base classes that have been explicitly registered continues, but this won't 
include unregistered complete implementations.

Either the compound classes need their own __subclasshook__ implementations, or 
the documentation needs to be updated to make it clear that without explicit 
registrations the issubclass() (and isinstance()) tests only apply to the One 
Trick Ponies.

----------
assignee: docs@python
components: Documentation, Library (Lib)
messages: 240060
nosy: docs@python, mjpieters
priority: normal
severity: normal
status: open
title: issubclass without registration only works for "one-trick pony" 
collections ABCs.

_______________________________________
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue23864>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to