Skip to content
Snippets Groups Projects
Unverified Commit 27e36657 authored by Jelle Zijlstra's avatar Jelle Zijlstra Committed by GitHub
Browse files

Improve the typing docs (#92264)

parent 1f631ae3
Branches
Tags
No related merge requests found
...@@ -125,7 +125,7 @@ Note that ``None`` as a type hint is a special case and is replaced by ...@@ -125,7 +125,7 @@ Note that ``None`` as a type hint is a special case and is replaced by
NewType NewType
======= =======
Use the :class:`NewType` helper class to create distinct types:: Use the :class:`NewType` helper to create distinct types::
from typing import NewType from typing import NewType
...@@ -154,7 +154,7 @@ accidentally creating a ``UserId`` in an invalid way:: ...@@ -154,7 +154,7 @@ accidentally creating a ``UserId`` in an invalid way::
Note that these checks are enforced only by the static type checker. At runtime, Note that these checks are enforced only by the static type checker. At runtime,
the statement ``Derived = NewType('Derived', Base)`` will make ``Derived`` a the statement ``Derived = NewType('Derived', Base)`` will make ``Derived`` a
class that immediately returns whatever parameter you pass it. That means callable that immediately returns whatever parameter you pass it. That means
the expression ``Derived(some_value)`` does not create a new class or introduce the expression ``Derived(some_value)`` does not create a new class or introduce
much overhead beyond that of a regular function call. much overhead beyond that of a regular function call.
...@@ -242,7 +242,7 @@ respectively. ...@@ -242,7 +242,7 @@ respectively.
See :pep:`612` for more information. See :pep:`612` for more information.
.. seealso:: .. seealso::
The documentation for :class:`ParamSpec` and :class:`Concatenate` provide The documentation for :class:`ParamSpec` and :class:`Concatenate` provides
examples of usage in ``Callable``. examples of usage in ``Callable``.
.. _generics: .. _generics:
...@@ -411,7 +411,7 @@ to this is that a list of types can be used to substitute a :class:`ParamSpec`:: ...@@ -411,7 +411,7 @@ to this is that a list of types can be used to substitute a :class:`ParamSpec`::
Furthermore, a generic with only one parameter specification variable will accept Furthermore, a generic with only one parameter specification variable will accept
parameter lists in the forms ``X[[Type1, Type2, ...]]`` and also parameter lists in the forms ``X[[Type1, Type2, ...]]`` and also
``X[Type1, Type2, ...]`` for aesthetic reasons. Internally, the latter is converted ``X[Type1, Type2, ...]`` for aesthetic reasons. Internally, the latter is converted
to the former and are thus equivalent:: to the former, so the following are equivalent::
>>> class X(Generic[P]): ... >>> class X(Generic[P]): ...
... ...
...@@ -515,7 +515,7 @@ manner. Use :data:`Any` to indicate that a value is dynamically typed. ...@@ -515,7 +515,7 @@ manner. Use :data:`Any` to indicate that a value is dynamically typed.
Nominal vs structural subtyping Nominal vs structural subtyping
=============================== ===============================
Initially :pep:`484` defined Python static type system as using Initially :pep:`484` defined the Python static type system as using
*nominal subtyping*. This means that a class ``A`` is allowed where *nominal subtyping*. This means that a class ``A`` is allowed where
a class ``B`` is expected if and only if ``A`` is a subclass of ``B``. a class ``B`` is expected if and only if ``A`` is a subclass of ``B``.
...@@ -710,7 +710,7 @@ These can be used as types in annotations and do not support ``[]``. ...@@ -710,7 +710,7 @@ These can be used as types in annotations and do not support ``[]``.
- :class:`classmethod`\s that are used as alternative constructors and return instances - :class:`classmethod`\s that are used as alternative constructors and return instances
of the ``cls`` parameter. of the ``cls`` parameter.
- Annotating an :meth:`object.__enter__` method which returns self. - Annotating an :meth:`~object.__enter__` method which returns self.
For more information, see :pep:`673`. For more information, see :pep:`673`.
...@@ -880,7 +880,6 @@ These can be used as types in annotations using ``[]``, each having a unique syn ...@@ -880,7 +880,6 @@ These can be used as types in annotations using ``[]``, each having a unique syn
def with_lock(f: Callable[Concatenate[Lock, P], R]) -> Callable[P, R]: def with_lock(f: Callable[Concatenate[Lock, P], R]) -> Callable[P, R]:
'''A type-safe decorator which provides a lock.''' '''A type-safe decorator which provides a lock.'''
global my_lock
def inner(*args: P.args, **kwargs: P.kwargs) -> R: def inner(*args: P.args, **kwargs: P.kwargs) -> R:
# Provide the lock as the first argument. # Provide the lock as the first argument.
return f(my_lock, *args, **kwargs) return f(my_lock, *args, **kwargs)
...@@ -1036,7 +1035,7 @@ These can be used as types in annotations using ``[]``, each having a unique syn ...@@ -1036,7 +1035,7 @@ These can be used as types in annotations using ``[]``, each having a unique syn
``no_type_check`` functionality that currently exists in the ``typing`` ``no_type_check`` functionality that currently exists in the ``typing``
module which completely disables typechecking annotations on a function module which completely disables typechecking annotations on a function
or a class, the ``Annotated`` type allows for both static typechecking or a class, the ``Annotated`` type allows for both static typechecking
of ``T`` (e.g., via mypy or Pyre, which can safely ignore ``x``) of ``T`` (which can safely ignore ``x``)
together with runtime access to ``x`` within a specific application. together with runtime access to ``x`` within a specific application.
Ultimately, the responsibility of how to interpret the annotations (if Ultimately, the responsibility of how to interpret the annotations (if
...@@ -1279,7 +1278,7 @@ These are not used in annotations. They are building blocks for creating generic ...@@ -1279,7 +1278,7 @@ These are not used in annotations. They are building blocks for creating generic
.. class:: TypeVarTuple .. class:: TypeVarTuple
Type variable tuple. A specialized form of :class:`Type variable <TypeVar>` Type variable tuple. A specialized form of :class:`type variable <TypeVar>`
that enables *variadic* generics. that enables *variadic* generics.
A normal type variable enables parameterization with a single type. A type A normal type variable enables parameterization with a single type. A type
...@@ -1602,7 +1601,7 @@ These are not used in annotations. They are building blocks for declaring types. ...@@ -1602,7 +1601,7 @@ These are not used in annotations. They are building blocks for declaring types.
The resulting class has an extra attribute ``__annotations__`` giving a The resulting class has an extra attribute ``__annotations__`` giving a
dict that maps the field names to the field types. (The field names are in dict that maps the field names to the field types. (The field names are in
the ``_fields`` attribute and the default values are in the the ``_fields`` attribute and the default values are in the
``_field_defaults`` attribute both of which are part of the namedtuple ``_field_defaults`` attribute, both of which are part of the :func:`~collections.namedtuple`
API.) API.)
``NamedTuple`` subclasses can also have docstrings and methods:: ``NamedTuple`` subclasses can also have docstrings and methods::
...@@ -1695,7 +1694,7 @@ These are not used in annotations. They are building blocks for declaring types. ...@@ -1695,7 +1694,7 @@ These are not used in annotations. They are building blocks for declaring types.
in 3.13. It may also be unsupported by static type checkers. in 3.13. It may also be unsupported by static type checkers.
The functional syntax should also be used when any of the keys are not valid The functional syntax should also be used when any of the keys are not valid
:ref:`identifiers`, for example because they are keywords or contain hyphens. :ref:`identifiers <identifiers>`, for example because they are keywords or contain hyphens.
Example:: Example::
# raises SyntaxError # raises SyntaxError
...@@ -1737,7 +1736,7 @@ These are not used in annotations. They are building blocks for declaring types. ...@@ -1737,7 +1736,7 @@ These are not used in annotations. They are building blocks for declaring types.
y: int y: int
z: int z: int
A ``TypedDict`` cannot inherit from a non-TypedDict class, A ``TypedDict`` cannot inherit from a non-\ ``TypedDict`` class,
except for :class:`Generic`. For example:: except for :class:`Generic`. For example::
class X(TypedDict): class X(TypedDict):
...@@ -2155,7 +2154,7 @@ Corresponding to other types in :mod:`collections.abc` ...@@ -2155,7 +2154,7 @@ Corresponding to other types in :mod:`collections.abc`
.. class:: Hashable .. class:: Hashable
An alias to :class:`collections.abc.Hashable` An alias to :class:`collections.abc.Hashable`.
.. class:: Reversible(Iterable[T_co]) .. class:: Reversible(Iterable[T_co])
...@@ -2167,7 +2166,7 @@ Corresponding to other types in :mod:`collections.abc` ...@@ -2167,7 +2166,7 @@ Corresponding to other types in :mod:`collections.abc`
.. class:: Sized .. class:: Sized
An alias to :class:`collections.abc.Sized` An alias to :class:`collections.abc.Sized`.
Asynchronous programming Asynchronous programming
"""""""""""""""""""""""" """"""""""""""""""""""""
...@@ -2388,12 +2387,12 @@ Functions and decorators ...@@ -2388,12 +2387,12 @@ Functions and decorators
.. seealso:: .. seealso::
`Unreachable Code and Exhaustiveness Checking `Unreachable Code and Exhaustiveness Checking
<https://typing.readthedocs.io/en/latest/source/unreachable.html>_` has more <https://typing.readthedocs.io/en/latest/source/unreachable.html>`__ has more
information about exhaustiveness checking with static typing. information about exhaustiveness checking with static typing.
.. versionadded:: 3.11 .. versionadded:: 3.11
.. function:: reveal_type(obj) .. function:: reveal_type(obj, /)
Reveal the inferred static type of an expression. Reveal the inferred static type of an expression.
...@@ -2465,9 +2464,9 @@ Functions and decorators ...@@ -2465,9 +2464,9 @@ Functions and decorators
the documentation for :func:`@overload <overload>`, the documentation for :func:`@overload <overload>`,
``get_overloads(process)`` will return a sequence of three function objects ``get_overloads(process)`` will return a sequence of three function objects
for the three defined overloads. If called on a function with no overloads, for the three defined overloads. If called on a function with no overloads,
``get_overloads`` returns an empty sequence. ``get_overloads()`` returns an empty sequence.
``get_overloads`` can be used for introspecting an overloaded function at ``get_overloads()`` can be used for introspecting an overloaded function at
runtime. runtime.
.. versionadded:: 3.11 .. versionadded:: 3.11
...@@ -2632,8 +2631,8 @@ Introspection helpers ...@@ -2632,8 +2631,8 @@ Introspection helpers
.. class:: ForwardRef .. class:: ForwardRef
A class used for internal typing representation of string forward references. A class used for internal typing representation of string forward references.
For example, ``list["SomeClass"]`` is implicitly transformed into For example, ``List["SomeClass"]`` is implicitly transformed into
``list[ForwardRef("SomeClass")]``. This class should not be instantiated by ``List[ForwardRef("SomeClass")]``. This class should not be instantiated by
a user, but may be used by introspection tools. a user, but may be used by introspection tools.
.. note:: .. note::
...@@ -2667,7 +2666,7 @@ Constant ...@@ -2667,7 +2666,7 @@ Constant
If ``from __future__ import annotations`` is used in Python 3.7 or later, If ``from __future__ import annotations`` is used in Python 3.7 or later,
annotations are not evaluated at function definition time. annotations are not evaluated at function definition time.
Instead, they are stored as strings in ``__annotations__``. Instead, they are stored as strings in ``__annotations__``.
This makes it unnecessary to use quotes around the annotation. This makes it unnecessary to use quotes around the annotation
(see :pep:`563`). (see :pep:`563`).
.. versionadded:: 3.5.2 .. versionadded:: 3.5.2
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment