mirror of
https://github.com/python/cpython.git
synced 2025-08-04 08:59:19 +00:00
Fix typing.TYPE_CHECKING docs to reflect PEP 649. (#134813)
typing.TYPE_CHECKING should no longer steer users towards manual or automatic stringization (and PEP 563); PEP 649 makes all that unnecessary.
This commit is contained in:
parent
fbbbc10055
commit
d7256ae4d7
1 changed files with 18 additions and 14 deletions
|
@ -3530,28 +3530,32 @@ Constant
|
||||||
.. data:: TYPE_CHECKING
|
.. data:: TYPE_CHECKING
|
||||||
|
|
||||||
A special constant that is assumed to be ``True`` by 3rd party static
|
A special constant that is assumed to be ``True`` by 3rd party static
|
||||||
type checkers. It is ``False`` at runtime.
|
type checkers. It's ``False`` at runtime.
|
||||||
|
|
||||||
|
A module which is expensive to import, and which only contain types
|
||||||
|
used for typing annotations, can be safely imported inside an
|
||||||
|
``if TYPE_CHECKING:`` block. This prevents the module from actually
|
||||||
|
being imported at runtime; annotations aren't eagerly evaluated
|
||||||
|
(see :pep:`649`) so using undefined symbols in annotations is
|
||||||
|
harmless--as long as you don't later examine them.
|
||||||
|
Your static type analysis tool will set ``TYPE_CHECKING`` to
|
||||||
|
``True`` during static type analysis, which means the module will
|
||||||
|
be imported and the types will be checked properly during such analysis.
|
||||||
|
|
||||||
Usage::
|
Usage::
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
import expensive_mod
|
import expensive_mod
|
||||||
|
|
||||||
def fun(arg: 'expensive_mod.SomeType') -> None:
|
def fun(arg: expensive_mod.SomeType) -> None:
|
||||||
local_var: expensive_mod.AnotherType = other_fun()
|
local_var: expensive_mod.AnotherType = other_fun()
|
||||||
|
|
||||||
The first type annotation must be enclosed in quotes, making it a
|
If you occasionally need to examine type annotations at runtime
|
||||||
"forward reference", to hide the ``expensive_mod`` reference from the
|
which may contain undefined symbols, use
|
||||||
interpreter runtime. Type annotations for local variables are not
|
:meth:`annotationlib.get_annotations` with a ``format`` parameter
|
||||||
evaluated, so the second annotation does not need to be enclosed in quotes.
|
of :attr:`annotationlib.Format.STRING` or
|
||||||
|
:attr:`annotationlib.Format.FORWARDREF` to safely retrieve the
|
||||||
.. note::
|
annotations without raising :exc:`NameError`.
|
||||||
|
|
||||||
If ``from __future__ import annotations`` is used,
|
|
||||||
annotations are not evaluated at function definition time.
|
|
||||||
Instead, they are stored as strings in ``__annotations__``.
|
|
||||||
This makes it unnecessary to use quotes around the annotation
|
|
||||||
(see :pep:`563`).
|
|
||||||
|
|
||||||
.. versionadded:: 3.5.2
|
.. versionadded:: 3.5.2
|
||||||
|
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue