Featureadvanced
Generic alias types
Also called GenericAlias, types.GenericAlias, list[int], __class_getitem__, __origin__, __args__, union object, types.UnionType, typing.Union, PEP 585, PEP 560.
At run time, list[int] is a types.GenericAlias object, made by list.__class_getitem__, and int | str is a union object. They keep their arguments, but Python does not check values against them.
- Language
- Python
- Proposals
- pep-585, pep-560, pep-604
Synopsis
import types
from typing import get_args, get_origin
t = dict[str, list[int]]
print(t, isinstance(t, types.GenericAlias))
print(get_origin(t), get_args(t))
d = t(a=[1, 2])
print(type(d), d)
dict[str, list[int]] True
<class 'dict'> (<class 'str'>, list[int])
<class 'dict'> {'a': [1, 2]}
A subscription of dict gives an alias object. The object keeps the class and the arguments, and get_origin and get_args read them. A call of the alias makes a plain dict.
Semantics
r1. "GenericAlias objects are generally created by subscripting a class."1 "GenericAlias objects are intended primarily for use with type annotations."1 PEP 585 "proposes to enable support for the generics syntax in all standard collections currently available in the typing module."2 Example: alias.
r2. The alias has the attributes __origin__, __args__ and __parameters__. __origin__ "points at the non-parameterized generic class".1 __args__ "is a tuple (possibly of length 1) of generic types passed to the original class_getitem() of the generic class".1 The functions typing.get_origin and typing.get_args read the same data, and they work for the forms of the typing module too. get_origin will "Get the unsubscripted version of a type".3 Example: alias.
r3. A subscription of a class calls __class_getitem__. "A class can generally only be parameterized if it defines the special class method class_getitem()."4 "Usually, the subscription of an object using square brackets will call the getitem() instance method defined on the object’s class. However, if the object being subscribed is itself a class, the class method class_getitem() may be called instead."4 PEP 560 added the method: "It is proposed to add two special methods class_getitem and mro_entries to the core CPython for better support of generic types."5 Examples: class-getitem, enum-index.
r4. "When defined on a class, class_getitem() is automatically a class method."4 It is for type hints only: "Using class_getitem() on any class for purposes other than type hinting is discouraged."4 For a generic class that the checkers understand, use a type parameter list or typing.Generic.4 Example: class-getitem.
r5. Python does not check values against an alias. "The Python runtime does not enforce type annotations. This extends to generic types and their type parameters."1 "Furthermore, parameterized generics erase type parameters during object creation".1 "The builtin functions isinstance() and issubclass() do not accept GenericAlias types for their second argument".1 Examples: unchecked, isinstance-alias.
r6. "A union object holds the value of the | (bitwise or) operation on multiple type objects."1 Unions compare as sets: "Unions of unions are flattened", "Redundant types are removed" and "When comparing unions, the order is ignored".1 isinstance accepts a union of classes. PEP 604 "allows it to appear in isinstance and issubclass calls."6 Example: union.
Examples
import types
class Box:
def __class_getitem__(cls, item: object) -> types.GenericAlias:
return types.GenericAlias(cls, item)
def __getitem__(self, key: int) -> str:
return f"item {key}"
print(Box[int], Box[int].__origin__ is Box)
print(Box()[3])
__main__.Box[int] True
item 3
Box[int] subscribes the class, so Python calls __class_getitem__. Box()[3] subscribes an object, so Python calls __getitem__ (rule r3). Mypy does not understand a custom __class_getitem__, as the data model says: "Custom implementations of class_getitem() on classes defined outside of the standard library may not be understood by third-party type-checkers such as mypy."4
$ mypy --strict box.py
box.py:12: error: The type "type[Box]" is not generic and not indexable [misc]
Found 1 error in 1 file (checked 1 source file)
from enum import Enum
class Color(Enum):
RED = "r"
BLUE = "b"
print(Color["RED"], type(Color).__name__)
Color.RED EnumType
The metaclass of Color defines __getitem__, so Color["RED"] looks up a member and does not make an alias (rule r3).
import typing
u = int | str
print(u, u == (str | int), (int | str) | int == u)
print(isinstance(3, u), isinstance(3.0, u))
print(typing.Optional[int] == (int | None))
int | str True True
True False
True
The order and the repeated int have no effect, and isinstance accepts the union (rule r6).
Versions
Since 3.9
The built-in collections accept subscription, from PEP 585. "In type annotations you can now use built-in collection types such as list and dict as generic types instead of importing the corresponding capitalized types (e.g. List or Dict) from typing."7
Since 3.10
Since 3.14
"Union objects are now instances of typing.Union. Previously, they were instances of types.UnionType, which remains an alias for typing.Union."1 "Use == to compare unions for equality, not is."8
Pitfalls
This code runs but gives a wrong answer on purpose.
t = list[str]
values = t([1, 2, 3])
print(values, type(values))
[1, 2, 3] <class 'list'>
The alias makes a list of numbers. The type argument str is not checked, and the result does not keep it (rule r5). The checker finds the numbers:
$ mypy --strict unchecked.py
unchecked.py:2: error: List item 0 has incompatible type "int"; expected "str" [list-item]
unchecked.py:2: error: List item 1 has incompatible type "int"; expected "str" [list-item]
unchecked.py:2: error: List item 2 has incompatible type "int"; expected "str" [list-item]
Found 3 errors in 1 file (checked 1 source file)
This code raises TypeError, on purpose.
print(isinstance([1], list))
print(isinstance([1], list[int]))
The checker reports the same line:
$ mypy --strict isalias.py
isalias.py:2: error: Parameterized generics cannot be used with class or instance checks [misc]
Found 1 error in 1 file (checked 1 source file)
To test a list at run time, test the list class and then each element (rule r5).
Comparison
In Python, list[int] is an ordinary object at run time, so a program can store it, print it and read its arguments. Java erases type arguments at run time too, but List<Integer> there is not a value. For generic classes that the checker understands, see Generic functions and classes. For the classes that support subscription, see collections.abc.
References
- Built-in Types, Python 3.15 documentation, Generic Alias Type; Special Attributes of GenericAlias objects; Union Type
- PEP 585: Type Hinting Generics In Standard Collections, Abstract
- typing, Support for type hints, Python 3.15 documentation, typing.get_origin; typing.get_args
- Data model, Python 3.15 documentation, 3.3.5. Emulating generic types; 3.3.5.1; 3.3.5.2
- PEP 560: Core support for typing module and generic types, Abstract
- PEP 604: Allow writing union types as X | Y, Abstract
- What’s New In Python 3.9, Type Hinting Generics in Standard Collections
- What’s New In Python 3.14, typing
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag T0EZRY Edit this page History Report an error Markdown