Python 3.9+Built-in typesterm
types.GenericAlias
annotation types
The type of an expression like list[int]: a parameterised built-in class used in annotations that keeps the original class and its type arguments.
Syntax
list[int] # → types.GenericAlias
list[int] creates no new class and checks nothing at run time: list[int]([1, 'a']) happily returns a list with a string. It cannot be passed to isinstance — that raises TypeError, so check isinstance(x, list). typing.get_origin and typing.get_args extract the original class and the arguments. Since Python 3.9 built-in collections support this syntax directly, without typing.List.
Examples
import types
import typing
alias = list[int]
print(type(alias) is types.GenericAlias) # → True
print(typing.get_origin(alias), typing.get_args(alias)) # → <class 'list'> (<class 'int'>,)
print(alias([1, 'a'])) # → [1, 'a'] — тип элементов не проверяется
isinstance([], list[int]) # → TypeError: параметризованный тип в isinstance нельзя
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy