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?
__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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With