Why check if cls is a class in __subclasshook__?

In the Python standard library documentation, an example implementation __subclasshook__:

class MyIterable(metaclass=ABCMeta):

[...]

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

The CPython implementation collections.abcdoes follow this format for most of the member functions __subclasshook__that it defines. What is the purpose of explicitly checking an argument cls?

+4
source share
1 answer

__subclasshook__inherited. Validation cls is MyIterableensures that specific subclasses MyIterableuse regular logic issubclassinstead of method validation __iter__. Otherwise, MyConcreteIterable(MyIterable)you will have a issubclass(list, MyConcreteIterable)refund for the class True.

+2

All Articles