TYPE_CHECKING to lazy imports¶
Stable ID: FEATURE-TYPE-CHECKING-TO-LAZY-IMPORTS
User-facing summary¶
Replaces each module-level if TYPE_CHECKING: block that only holds imports by those imports, written as
PEP 810 lazy imports. ruff has no rule for this
(astral-sh/ruff#29378). The recipe finds and
rewrites the blocks with pattern matching.
Before:
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from collections.abc import Callable
from pathlib import Path
After:
from typing import TYPE_CHECKING
lazy from collections.abc import Callable
lazy from pathlib import Path
Inputs¶
A .py file whose project targets Python 3.15 or later. Before 3.15, lazy is a syntax error.
Outputs / effects¶
- A block
if TYPE_CHECKING:,if typing.TYPE_CHECKING:orif False:(the older form) is replaced by its imports, each withlazyin front and dedented to module level. An import that is already lazy keeps a singlelazy. - The file is changed in place.
from typing import TYPE_CHECKINGstays.ruff check --select F401 --fixremoves it once nothing uses it.
Known limitations¶
- The comment on the
ifline and the comments between theifand its first import are lost. A comment above theif, a comment after an import and a comment between two imports are kept. - A comment after the last import keeps its indentation.
ruff formatdedents it. - When a block holds one import that spans several lines, the lines inside its parentheses keep their indentation. The
code stays valid.
ruff formatdedents them. - Any name
TYPE_CHECKINGis matched, also a variable of the project with that name. if t.TYPE_CHECKING:afterimport typing as tis not converted.if 0:is converted likeif False:, since the pattern compares values with==.
Constraints¶
A block stays unchanged when:
- it has an
elseorelif; - it holds a statement that is not an import;
- it holds a star import or a
__future__import, which PEP 810 does not allow to be lazy; - it is not at module level, for example inside a function or a
try.
A lazy import still runs, when its name is first used. Under TYPE_CHECKING, it never ran:
- Something that evaluates annotations, such as
typing.get_type_hints, now imports the module. A module that only type checkers know (_typeshed) then raisesModuleNotFoundErrorinstead ofNameError. - A filter set with
sys.set_lazy_imports_filtercan make a lazy import eager. Such a module then fails at the import line.
Related concepts¶
Verified by test modules¶
test/recipes/test_type_checking_to_lazy.py
Implemented by code modules¶
- Refactoring recipes
src/renaissance/recipes/type_checking_to_lazy.py
API entry points¶
python src/rejuvenation/cli.py refactor TypeCheckingToLazy [FILE]
Without FILE, every Python source under the working directory is processed.
Change considerations¶
TYPE_CHECKING_BLOCKSholds the patterns. A new form of the block is a new pattern there._can_be_lazydecides which imports PEP 810 allows to be lazy.