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
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
CodePudding user response:
Quoting the documentation for the issubclass
function (emphasis mine):
Return
True
if class is a subclass (direct, indirect, or virtual) ofclassinfo
.
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()
andissubclass()
; 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)