Python Glossary Русский

Python 3.5+Annotations & typingterm

TYPE_CHECKING

import

A boolean constant that is True only during static analysis (mypy, pyright). Lets you import types for annotations alone, avoiding circular imports at runtime.

Syntax

from typing import TYPE_CHECKING
if TYPE_CHECKING:
    from module import SomeType

Because the import under if TYPE_CHECKING never runs, the name must not end up in code that is actually evaluated — default values, cast(), isinstance. In annotations, since Python 3.14, you may write it unquoted: annotations are evaluated lazily and the module loads fine (before 3.14 you needed quotes or from __future__ import annotations, otherwise NameError on import). The side effect remains: anything that reads types at runtime (typing.get_type_hints, __annotations__, dataclasses, validation libraries) cannot resolve such a name and gets NameError.

Examples

from typing import TYPE_CHECKING
print(TYPE_CHECKING)  # → False  (в рантайме)
if TYPE_CHECKING:
    from collections import OrderedDict
from typing import TYPE_CHECKING
def process(path: 'str') -> None:
    print(path)
process('test')  # → test
print(bool(TYPE_CHECKING))  # → False

See also

Open in the full glossarydocs.python.orgReport an inaccuracy