Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How list_iterator is sub-class of Iterator even though MROs are different?

I have the following code. From the output the MROs are different but still issubclass returns true. Can someone explain how Python finds they are equal?

My understanding is that MRO show the inheritance tree of classes. And classes with different inheritance tree (MRO) should not satisfy sub-class validation. I am using Python-3.9.5 on Windows-10

Code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

from collections.abc import Iterator

it_type = type(iter([]))
print(it_type.__mro__)
print(Iterator.__mro__)
print(issubclass(it_type, Iterator))

Output

(<class 'list_iterator'>, <class 'object'>)
(<class 'collections.abc.Iterator'>, <class 'collections.abc.Iterable'>, <class 'object'>)
True

>Solution :

Quoting the documentation for the issubclass function (emphasis mine):

Return True if class is a subclass (direct, indirect, or virtual) of classinfo.

Following the link to the definition of a virtual subclass:

ABCs introduce virtual subclasses, which are classes that don’t inherit from a class but are still recognized by isinstance() and issubclass(); see the abc module documentation.

Following that link to the abc module documentation:

An ABC can be subclassed directly, and then acts as a mix-in class. You can also register unrelated concrete classes (even built-in classes) and unrelated ABCs as “virtual subclasses” – these and their descendants will be considered subclasses of the registering ABC by the built-in issubclass() function, but the registering ABC won’t show up in their MRO (Method Resolution Order)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading