PeopleMoutainPeopleSea
PeopleMoutainPeopleSea

Reputation: 1512

How come Python3 typing.List is a subclass of list and list is also a subclass of typing.List?

I tested this simple code and find something confuses me. Run the following code in Python 3.6 and both statements returns True. Why?

import typing
print(issubclass(list, typing.List))  # print True
print(issubclass(typing.List, list))  # print True

Can someone give me some explanation on this?

Upvotes: 3

Views: 504

Answers (1)

zvone
zvone

Reputation: 19362

Strictly speaking, list is not a subclass of typing.List. To see what list is actually a subclass of, you can take a look at its MRO:

>>> list.__mro__
(<class 'list'>, <class 'object'>)

On the other hand, the MRO of typing.List shows that it actually is a subclass of list, as well as of many other classes:

>>> typing.List.__mro__
(typing.List, <class 'list'>, typing.MutableSequence, <class 'collections.abc.MutableSequence'>, typing.Sequence, <class 'collections.abc.Sequence'>, typing.Reversible, <class 'collections.abc.Reversible'>, typing.Collection, <class 'collections.abc.Collection'>, <class 'collections.abc.Sized'>, typing.Iterable, <class 'collections.abc.Iterable'>, typing.Container, <class 'collections.abc.Container'>, typing.Generic, <class 'object'>)

So, why does Python say that list is a subclass of typing.List?

Well, that is the whole point of typing.List. To pretend to be a base class of list.

How is it done?

Using Abstract Base Classes. See what Python doc says about them:

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.

You can see from its MRO that typing.List inherits from many ABC's, which list recognizes as its base classes, e.g.:

>>> issubclass(list, collections.abc.MutableSequence)
True
>>> issubclass(list, collections.abc.Collection)
True
>>> issubclass(list, collections.abc.Container)
True

Upvotes: 3

Related Questions