typing.TYPE_CHECKING
Purpose
typing.TYPE_CHECKING is a boolean flag, it’s True during static type checking(e.g. mypy), and it’s False at runtime.
Use Case
It is primarily used to guard imports or code blocks that are only necessary for type checking and should not be executed at runtime.
Circular Import
Circular import means two modules import each other.
1 | # module_a.py |
1 | # module_b.py |
When type hints introduce circular dependencies between modules, TYPE_CHECKING can be used to conditionally import modules only during type checking, preventing runtime import errors.
Notice: circular import error may occur for several reasons, e.g. function invocation or type annotation,
typing.TYPE_CHECKINGis only useful for type annotation.
1 | from typing import TYPE_CHECKING |
Avoid unnecessary import cost
If the module is only used as a type annotation, typing.TYPE_CHECKING avoid importing it at runtime so that improve the efficiency.
1 | from typing import TYPE_CHECKING |
from __future__ import annotation
Instead of immediately evaluating the type hints when a function or class is defined, it stores them as string literals.
1 | from __future__ import annotation |