pythonpython-3.xdictionarymethod-resolution-order

dict_items class not showing correct class inheritance


I was going through this answer where I found that <class 'dict_items'> is a subclass of <class 'collections.abc.ItemsView'>. You can test this using:

>>> import collections
>>> issubclass({}.items().__class__, collections.abc.ItemsView)
True

However, I went a bit further and checked the __mro__ attribute of <class 'dict_items'> and as this is a subclass of <class 'collections.abc.ItemsView'>, it should be printed when I print the __mro__ attribute but it isn't there.

>>> {}.items().__class__.__mro__
(<class 'dict_items'>, <class 'object'>)

I also checked the subclasses of <class 'collections.abc.ItemsView'>

>>> collections.abc.ItemsView.__subclasses__()
[<class 'collections._OrderedDictItemsView'>]

Can anyone tell me why am I getting this?


Solution

  • ItemsView explicitly registers DictItems as a "virtual subclass" of it, so that's what's being checked here.

    Even in cases where a type isn't registered explicitly though, issubclass can still report that one type is a subtype of another even when that isn't literally true. issubclass doesn't necessarily tell you if one thing is a literal subclass of another, since that behavior can be overridden:

    These ABCs override object.__subclasshook__() to support testing an interface by verifying the required methods are present and have not been set to None. This only works for simple interfaces. More complex interfaces require registration or direct subclassing.