Skip to content

Commit d7256ae

Browse files
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.
1 parent fbbbc10 commit d7256ae

File tree

1 file changed

+18
-14
lines changed

1 file changed

+18
-14
lines changed

Doc/library/typing.rst

Lines changed: 18 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3530,28 +3530,32 @@ Constant
35303530
.. data:: TYPE_CHECKING
35313531

35323532
A special constant that is assumed to be ``True`` by 3rd party static
3533-
type checkers. It is ``False`` at runtime.
3533+
type checkers. It's ``False`` at runtime.
3534+
3535+
A module which is expensive to import, and which only contain types
3536+
used for typing annotations, can be safely imported inside an
3537+
``if TYPE_CHECKING:`` block. This prevents the module from actually
3538+
being imported at runtime; annotations aren't eagerly evaluated
3539+
(see :pep:`649`) so using undefined symbols in annotations is
3540+
harmless--as long as you don't later examine them.
3541+
Your static type analysis tool will set ``TYPE_CHECKING`` to
3542+
``True`` during static type analysis, which means the module will
3543+
be imported and the types will be checked properly during such analysis.
35343544

35353545
Usage::
35363546

35373547
if TYPE_CHECKING:
35383548
import expensive_mod
35393549

3540-
def fun(arg: 'expensive_mod.SomeType') -> None:
3550+
def fun(arg: expensive_mod.SomeType) -> None:
35413551
local_var: expensive_mod.AnotherType = other_fun()
35423552

3543-
The first type annotation must be enclosed in quotes, making it a
3544-
"forward reference", to hide the ``expensive_mod`` reference from the
3545-
interpreter runtime. Type annotations for local variables are not
3546-
evaluated, so the second annotation does not need to be enclosed in quotes.
3547-
3548-
.. note::
3549-
3550-
If ``from __future__ import annotations`` is used,
3551-
annotations are not evaluated at function definition time.
3552-
Instead, they are stored as strings in ``__annotations__``.
3553-
This makes it unnecessary to use quotes around the annotation
3554-
(see :pep:`563`).
3553+
If you occasionally need to examine type annotations at runtime
3554+
which may contain undefined symbols, use
3555+
:meth:`annotationlib.get_annotations` with a ``format`` parameter
3556+
of :attr:`annotationlib.Format.STRING` or
3557+
:attr:`annotationlib.Format.FORWARDREF` to safely retrieve the
3558+
annotations without raising :exc:`NameError`.
35553559

35563560
.. versionadded:: 3.5.2
35573561

0 commit comments

Comments
 (0)