Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why check if cls is the class in __subclasshook__?

In the Python standard library documentation, the example implementation of __subclasshook__ is:

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

CPython's implementation of collections.abc indeed follows this format for most of the __subclasshook__ member functions it defines. What is the purpose of explicitly checking the cls argument?

like image 445
Praxeolitic Avatar asked Mar 08 '16 03:03

Praxeolitic


1 Answers

__subclasshook__ is inherited. The cls is MyIterable check ensures that concrete subclasses of MyIterable use the regular issubclass logic instead of checking for an __iter__ method. Otherwise, for a class MyConcreteIterable(MyIterable), you would have issubclass(list, MyConcreteIterable) returning True.

like image 170
user2357112 supports Monica Avatar answered Nov 12 '22 23:11

user2357112 supports Monica