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?
What use would an IS-A relationship between
List[str]
andSequence[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 GenericMeta
s __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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With