@@ -3530,28 +3530,32 @@ Constant
3530
3530
.. data :: TYPE_CHECKING
3531
3531
3532
3532
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.
3534
3544
3535
3545
Usage::
3536
3546
3537
3547
if TYPE_CHECKING:
3538
3548
import expensive_mod
3539
3549
3540
- def fun(arg: ' expensive_mod.SomeType' ) -> None:
3550
+ def fun(arg: expensive_mod.SomeType) -> None:
3541
3551
local_var: expensive_mod.AnotherType = other_fun()
3542
3552
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 `.
3555
3559
3556
3560
.. versionadded :: 3.5.2
3557
3561
0 commit comments