Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is List[str] not a subclass of Sequence[str]

List is a subclass of Sequence:

>>> from typing import List, Sequence
>>> issubclass(List, Sequence)
True

but List[str] is not a subclass of Sequence[str]:

>>> issubclass(List[str], Sequence[str])
False

Why?

like image 532
Michael Amrhein Avatar asked Jul 17 '16 20:07

Michael Amrhein


1 Answers

What use would an IS-A relationship between List[str] and Sequence[str] have when annotating?

This is the major point to take away. Checking if a type is a subtype of another type is not generally something you should be doing while type annotating your code. This is generally something that has been noticed and is the reason why there's a debate on the nuking of __subclasscheck__.

As Mark Shannon states in a comment:

It is meaningful to check whether a type is a subtype of a type, but that is the job of a static checker and doesn't belong in the typing module.

Either way, the checks are all made in GenericMetas __subclasscheck__, the metaclass for generic types

As is, the current implementation is more focused on cases where the container type is similar but their sub-scripted types differ, in this case, checks are made depending on if the sub-scripted types are covariant or contravariant. For example, List types are neither, as such, checking for a subtype relationship with:

issubclass(List[bool], List[int])  # checks if bool == int  

returns false. For sequences, the types are covariant, as such, the following yields True:

issubclass(Sequence[bool], Sequence[int])  # checks if bool is a subclass of int

On the other hand, for types without a specified type (as in your first case):

issubclass(List, Sequence)

__subclasscheck__ in GenericMeta will delegate to __subclasscheck__ in ABCMeta where it will evaluate to True.

Finally, if the two types are different, as in:

issubclass(List[str], Sequence[str])

and the the base class in the issubclass call is an instance of GenericMeta, False is returned; this condition is satisfied for most of the types in typing.

Whatever the case it is worth mentioning that this might not exist in a future release, or, its behaviour might be completely different; the module is still provisional.

like image 78
Dimitris Fasarakis Hilliard Avatar answered Sep 28 '22 18:09

Dimitris Fasarakis Hilliard