Skip to content

Commit 5915a1f

Browse files
gh-132467: Document and test that generic aliases are not classes (#133504)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
1 parent 58beae7 commit 5915a1f

3 files changed

Lines changed: 88 additions & 54 deletions

File tree

Doc/library/stdtypes.rst

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5927,6 +5927,15 @@ creation::
59275927
>>> type(l)
59285928
<class 'list'>
59295929

5930+
5931+
Instances of ``GenericAlias`` are not classes at runtime, even though they behave like classes (they can be instantiated and subclassed)::
5932+
5933+
>>> import inspect
5934+
>>> inspect.isclass(list[int])
5935+
False
5936+
5937+
This is true for :ref:`user-defined generics <user-defined-generics>` also.
5938+
59305939
Calling :func:`repr` or :func:`str` on a generic shows the parameterized type::
59315940

59325941
>>> repr(list[int])

Lib/test/test_typing.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5848,6 +5848,27 @@ def foo(x: T):
58485848

58495849
foo(42)
58505850

5851+
def test_genericalias_instance_isclass(self):
5852+
# test against user-defined generic classes
5853+
T = TypeVar('T')
5854+
5855+
class Node(Generic[T]):
5856+
def __init__(self, label: T,
5857+
left: 'Node[T] | None' = None,
5858+
right: 'Node[T] | None' = None):
5859+
self.label = label
5860+
self.left = left
5861+
self.right = right
5862+
5863+
self.assertTrue(inspect.isclass(Node))
5864+
self.assertFalse(inspect.isclass(Node[int]))
5865+
self.assertFalse(inspect.isclass(Node[str]))
5866+
5867+
# test against standard generic classes
5868+
self.assertFalse(inspect.isclass(set[int]))
5869+
self.assertFalse(inspect.isclass(list[bytes]))
5870+
self.assertFalse(inspect.isclass(dict[str, str]))
5871+
58515872
def test_implicit_any(self):
58525873
T = TypeVar('T')
58535874

Lib/typing.py

Lines changed: 58 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -1343,32 +1343,35 @@ def __dir__(self):
13431343

13441344

13451345
class _GenericAlias(_BaseGenericAlias, _root=True):
1346-
# The type of parameterized generics.
1347-
#
1348-
# That is, for example, `type(List[int])` is `_GenericAlias`.
1349-
#
1350-
# Objects which are instances of this class include:
1351-
# * Parameterized container types, e.g. `Tuple[int]`, `List[int]`.
1352-
# * Note that native container types, e.g. `tuple`, `list`, use
1353-
# `types.GenericAlias` instead.
1354-
# * Parameterized classes:
1355-
# class C[T]: pass
1356-
# # C[int] is a _GenericAlias
1357-
# * `Callable` aliases, generic `Callable` aliases, and
1358-
# parameterized `Callable` aliases:
1359-
# T = TypeVar('T')
1360-
# # _CallableGenericAlias inherits from _GenericAlias.
1361-
# A = Callable[[], None] # _CallableGenericAlias
1362-
# B = Callable[[T], None] # _CallableGenericAlias
1363-
# C = B[int] # _CallableGenericAlias
1364-
# * Parameterized `Final`, `ClassVar`, `TypeForm`, `TypeGuard`, and `TypeIs`:
1365-
# # All _GenericAlias
1366-
# Final[int]
1367-
# ClassVar[float]
1368-
# TypeForm[bytes]
1369-
# TypeGuard[bool]
1370-
# TypeIs[range]
1371-
1346+
"""The type of parameterized generics.
1347+
1348+
That is, for example, `type(List[int])` is `_GenericAlias`.
1349+
1350+
Objects which are instances of this class include:
1351+
* Parameterized container types, e.g. `Tuple[int]`, `List[int]`.
1352+
* Note that native container types, e.g. `tuple`, `list`, use
1353+
`types.GenericAlias` instead.
1354+
* Parameterized classes:
1355+
class C[T]: pass
1356+
# C[int] is a _GenericAlias
1357+
* `Callable` aliases, generic `Callable` aliases, and
1358+
parameterized `Callable` aliases:
1359+
T = TypeVar('T')
1360+
# _CallableGenericAlias inherits from _GenericAlias.
1361+
A = Callable[[], None] # _CallableGenericAlias
1362+
B = Callable[[T], None] # _CallableGenericAlias
1363+
C = B[int] # _CallableGenericAlias
1364+
* Parameterized `Final`, `ClassVar`, `TypeForm`, `TypeGuard`, and `TypeIs`:
1365+
# All _GenericAlias
1366+
Final[int]
1367+
ClassVar[float]
1368+
TypeForm[bytearray]
1369+
TypeGuard[bool]
1370+
TypeIs[range]
1371+
1372+
Note that instances of this class are not classes (e.g by `inspect.isclass`),
1373+
even though they behave like them.
1374+
"""
13721375
def __init__(self, origin, args, *, inst=True, name=None):
13731376
super().__init__(origin, inst=inst, name=name)
13741377
if not isinstance(args, tuple):
@@ -1400,20 +1403,21 @@ def __ror__(self, left):
14001403

14011404
@_tp_cache
14021405
def __getitem__(self, args):
1403-
# Parameterizes an already-parameterized object.
1404-
#
1405-
# For example, we arrive here doing something like:
1406-
# T1 = TypeVar('T1')
1407-
# T2 = TypeVar('T2')
1408-
# T3 = TypeVar('T3')
1409-
# class A(Generic[T1]): pass
1410-
# B = A[T2] # B is a _GenericAlias
1411-
# C = B[T3] # Invokes _GenericAlias.__getitem__
1412-
#
1413-
# We also arrive here when parameterizing a generic `Callable` alias:
1414-
# T = TypeVar('T')
1415-
# C = Callable[[T], None]
1416-
# C[int] # Invokes _GenericAlias.__getitem__
1406+
"""Parameterizes an already-parameterized object.
1407+
1408+
For example, we arrive here doing something like:
1409+
T1 = TypeVar('T1')
1410+
T2 = TypeVar('T2')
1411+
T3 = TypeVar('T3')
1412+
class A(Generic[T1]): pass
1413+
B = A[T2] # B is a _GenericAlias
1414+
C = B[T3] # Invokes _GenericAlias.__getitem__
1415+
1416+
We also arrive here when parameterizing a generic `Callable` alias:
1417+
T = TypeVar('T')
1418+
C = Callable[[T], None]
1419+
C[int] # Invokes _GenericAlias.__getitem__
1420+
"""
14171421

14181422
if self.__origin__ in (Generic, Protocol):
14191423
# Can't subscript Generic[...] or Protocol[...].
@@ -1430,20 +1434,20 @@ def __getitem__(self, args):
14301434
return r
14311435

14321436
def _determine_new_args(self, args):
1433-
# Determines new __args__ for __getitem__.
1434-
#
1435-
# For example, suppose we had:
1436-
# T1 = TypeVar('T1')
1437-
# T2 = TypeVar('T2')
1438-
# class A(Generic[T1, T2]): pass
1439-
# T3 = TypeVar('T3')
1440-
# B = A[int, T3]
1441-
# C = B[str]
1442-
# `B.__args__` is `(int, T3)`, so `C.__args__` should be `(int, str)`.
1443-
# Unfortunately, this is harder than it looks, because if `T3` is
1444-
# anything more exotic than a plain `TypeVar`, we need to consider
1445-
# edge cases.
1446-
1437+
"""Determines new __args__ for __getitem__.
1438+
1439+
For example, suppose we had:
1440+
T1 = TypeVar('T1')
1441+
T2 = TypeVar('T2')
1442+
class A(Generic[T1, T2]): pass
1443+
T3 = TypeVar('T3')
1444+
B = A[int, T3]
1445+
C = B[str]
1446+
`B.__args__` is `(int, T3)`, so `C.__args__` should be `(int, str)`.
1447+
Unfortunately, this is harder than it looks, because if `T3` is
1448+
anything more exotic than a plain `TypeVar`, we need to consider
1449+
edge cases.
1450+
"""
14471451
params = self.__parameters__
14481452
# In the example above, this would be {T3: str}
14491453
for param in params:

0 commit comments

Comments
 (0)