Skip to content

Commit 577d7c4

Browse files
authoredOct 28, 2020
[3.9] bpo-41805: Documentation for PEP 585 (GH-22615) (GH-23016)
Backport of #22615 to 3.9 since that couldn't be auto-merged due to conflicts.
1 parent 24a7c29 commit 577d7c4

File tree

4 files changed

+211
-0
lines changed

4 files changed

+211
-0
lines changed
 

‎Doc/glossary.rst

+7
Original file line numberDiff line numberDiff line change
@@ -483,6 +483,13 @@ Glossary
483483
See also the :term:`single dispatch` glossary entry, the
484484
:func:`functools.singledispatch` decorator, and :pep:`443`.
485485

486+
generic type
487+
A :term:`type` that can be parameterized; typically a container like
488+
:class:`list`. Used for :term:`type hints <type hint>` and
489+
:term:`annotations <annotation>`.
490+
491+
See :pep:`483` for more details, and :mod:`typing` or
492+
:ref:`generic alias type <types-genericalias>` for its uses.
486493

487494
GIL
488495
See :term:`global interpreter lock`.

‎Doc/library/stdtypes.rst

+193
Original file line numberDiff line numberDiff line change
@@ -4731,6 +4731,199 @@ Compared to the overhead of setting up the runtime context, the overhead of a
47314731
single class dictionary lookup is negligible.
47324732

47334733

4734+
.. _types-genericalias:
4735+
4736+
Generic Alias Type
4737+
==================
4738+
4739+
.. index::
4740+
object: GenericAlias
4741+
pair: Generic; Alias
4742+
4743+
``GenericAlias`` objects are created by subscripting a class (usually a
4744+
container), such as ``list[int]``. They are intended primarily for
4745+
:term:`type annotations <annotation>`.
4746+
4747+
Usually, the :ref:`subscription <subscriptions>` of container objects calls the
4748+
method :meth:`__getitem__` of the object. However, the subscription of some
4749+
containers' classes may call the classmethod :meth:`__class_getitem__` of the
4750+
class instead. The classmethod :meth:`__class_getitem__` should return a
4751+
``GenericAlias`` object.
4752+
4753+
.. note::
4754+
If the :meth:`__getitem__` of the class' metaclass is present, it will take
4755+
precedence over the :meth:`__class_getitem__` defined in the class (see
4756+
:pep:`560` for more details).
4757+
4758+
The ``GenericAlias`` object acts as a proxy for :term:`generic types
4759+
<generic type>`, implementing *parameterized generics* - a specific instance
4760+
of a generic which provides the types for container elements.
4761+
4762+
The user-exposed type for the ``GenericAlias`` object can be accessed from
4763+
:data:`types.GenericAlias` and used for :func:`isinstance` checks.
4764+
4765+
.. describe:: T[X, Y, ...]
4766+
4767+
Creates a ``GenericAlias`` representing a type ``T`` containing elements
4768+
of types *X*, *Y*, and more depending on the ``T`` used.
4769+
For example, a function expecting a :class:`list` containing
4770+
:class:`float` elements::
4771+
4772+
def average(values: list[float]) -> float:
4773+
return sum(values) / len(values)
4774+
4775+
Another example for :term:`mapping` objects, using a :class:`dict`, which
4776+
is a generic type expecting two type parameters representing the key type
4777+
and the value type. In this example, the function expects a ``dict`` with
4778+
keys of type :class:`str` and values of type :class:`int`::
4779+
4780+
def send_post_request(url: str, body: dict[str, int]) -> None:
4781+
...
4782+
4783+
The builtin functions :func:`isinstance` and :func:`issubclass` do not accept
4784+
``GenericAlias`` types for their second argument::
4785+
4786+
>>> isinstance([1, 2], list[str])
4787+
Traceback (most recent call last):
4788+
File "<stdin>", line 1, in <module>
4789+
TypeError: isinstance() argument 2 cannot be a parameterized generic
4790+
4791+
The Python runtime does not enforce :term:`type annotations <annotation>`.
4792+
This extends to generic types and their type parameters. When creating
4793+
an object from a ``GenericAlias``, container elements are not checked
4794+
against their type. For example, the following code is discouraged, but will
4795+
run without errors::
4796+
4797+
>>> t = list[str]
4798+
>>> t([1, 2, 3])
4799+
[1, 2, 3]
4800+
4801+
Furthermore, parameterized generics erase type parameters during object
4802+
creation::
4803+
4804+
>>> t = list[str]
4805+
>>> type(t)
4806+
<class 'types.GenericAlias'>
4807+
4808+
>>> l = t()
4809+
>>> type(l)
4810+
<class 'list'>
4811+
4812+
Calling :func:`repr` or :func:`str` on a generic shows the parameterized type::
4813+
4814+
>>> repr(list[int])
4815+
'list[int]'
4816+
4817+
>>> str(list[int])
4818+
'list[int]'
4819+
4820+
The :meth:`__getitem__` method of generics will raise an exception to disallow
4821+
mistakes like ``dict[str][str]``::
4822+
4823+
>>> dict[str][str]
4824+
Traceback (most recent call last):
4825+
File "<stdin>", line 1, in <module>
4826+
TypeError: There are no type variables left in dict[str]
4827+
4828+
However, such expressions are valid when :ref:`type variables <generics>` are
4829+
used. The index must have as many elements as there are type variable items
4830+
in the ``GenericAlias`` object's :attr:`__args__ <genericalias.__args__>`. ::
4831+
4832+
>>> from typing import TypeVar
4833+
>>> Y = TypeVar('Y')
4834+
>>> dict[str, Y][int]
4835+
dict[str, int]
4836+
4837+
4838+
Standard Generic Collections
4839+
----------------------------
4840+
4841+
These standard library collections support parameterized generics.
4842+
4843+
* :class:`tuple`
4844+
* :class:`list`
4845+
* :class:`dict`
4846+
* :class:`set`
4847+
* :class:`frozenset`
4848+
* :class:`type`
4849+
* :class:`collections.deque`
4850+
* :class:`collections.defaultdict`
4851+
* :class:`collections.OrderedDict`
4852+
* :class:`collections.Counter`
4853+
* :class:`collections.ChainMap`
4854+
* :class:`collections.abc.Awaitable`
4855+
* :class:`collections.abc.Coroutine`
4856+
* :class:`collections.abc.AsyncIterable`
4857+
* :class:`collections.abc.AsyncIterator`
4858+
* :class:`collections.abc.AsyncGenerator`
4859+
* :class:`collections.abc.Iterable`
4860+
* :class:`collections.abc.Iterator`
4861+
* :class:`collections.abc.Generator`
4862+
* :class:`collections.abc.Reversible`
4863+
* :class:`collections.abc.Container`
4864+
* :class:`collections.abc.Collection`
4865+
* :class:`collections.abc.Callable`
4866+
* :class:`collections.abc.Set`
4867+
* :class:`collections.abc.MutableSet`
4868+
* :class:`collections.abc.Mapping`
4869+
* :class:`collections.abc.MutableMapping`
4870+
* :class:`collections.abc.Sequence`
4871+
* :class:`collections.abc.MutableSequence`
4872+
* :class:`collections.abc.ByteString`
4873+
* :class:`collections.abc.MappingView`
4874+
* :class:`collections.abc.KeysView`
4875+
* :class:`collections.abc.ItemsView`
4876+
* :class:`collections.abc.ValuesView`
4877+
* :class:`contextlib.AbstractContextManager`
4878+
* :class:`contextlib.AbstractAsyncContextManager`
4879+
* :ref:`re.Pattern <re-objects>`
4880+
* :ref:`re.Match <match-objects>`
4881+
4882+
4883+
Special Attributes of Generic Alias
4884+
-----------------------------------
4885+
4886+
All parameterized generics implement special read-only attributes.
4887+
4888+
.. attribute:: genericalias.__origin__
4889+
4890+
This attribute points at the non-parameterized generic class::
4891+
4892+
>>> list[int].__origin__
4893+
<class 'list'>
4894+
4895+
4896+
.. attribute:: genericalias.__args__
4897+
4898+
This attribute is a :class:`tuple` (possibly of length 1) of generic
4899+
types passed to the original :meth:`__class_getitem__`
4900+
of the generic container::
4901+
4902+
>>> dict[str, list[int]].__args__
4903+
(<class 'str'>, list[int])
4904+
4905+
4906+
.. attribute:: genericalias.__parameters__
4907+
4908+
This attribute is a lazily computed tuple (possibly empty) of unique type
4909+
variables found in ``__args__``::
4910+
4911+
>>> from typing import TypeVar
4912+
4913+
>>> T = TypeVar('T')
4914+
>>> list[T].__parameters__
4915+
(~T,)
4916+
4917+
4918+
.. seealso::
4919+
4920+
* :pep:`585` -- "Type Hinting Generics In Standard Collections"
4921+
* :meth:`__class_getitem__` -- Used to implement parameterized generics.
4922+
* :ref:`generics` -- Generics in the :mod:`typing` module.
4923+
4924+
.. versionadded:: 3.9
4925+
4926+
47344927
.. _typesother:
47354928

47364929
Other Built-in Types

‎Doc/library/types.rst

+8
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,14 @@ Standard names are defined for the following types:
242242
Defaults to ``None``. Previously the attribute was optional.
243243

244244

245+
.. data:: GenericAlias
246+
247+
The type of :ref:`parameterized generics <types-genericalias>` such as
248+
``list[int]``.
249+
250+
.. versionadded:: 3.9
251+
252+
245253
.. class:: TracebackType(tb_next, tb_frame, tb_lasti, tb_lineno)
246254

247255
The type of traceback objects such as found in ``sys.exc_info()[2]``.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Documented :ref:`generic alias type <types-genericalias>` and
2+
:data:`types.GenericAlias`. Also added an entry in glossary for
3+
:term:`generic types <generic type>`.

0 commit comments

Comments
 (0)
Please sign in to comment.