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: or if False: (the older form) is replaced by its imports, each with lazy in front and dedented to module level. An import that is already lazy keeps a single lazy.
  • The file is changed in place.
  • from typing import TYPE_CHECKING stays. ruff check --select F401 --fix removes it once nothing uses it.

Known limitations

  • The comment on the if line and the comments between the if and its first import are lost. A comment above the if, a comment after an import and a comment between two imports are kept.
  • A comment after the last import keeps its indentation. ruff format dedents it.
  • When a block holds one import that spans several lines, the lines inside its parentheses keep their indentation. The code stays valid. ruff format dedents them.
  • Any name TYPE_CHECKING is matched, also a variable of the project with that name.
  • if t.TYPE_CHECKING: after import typing as t is not converted.
  • if 0: is converted like if False:, since the pattern compares values with ==.

Constraints

A block stays unchanged when:

  • it has an else or elif;
  • 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 raises ModuleNotFoundError instead of NameError.
  • A filter set with sys.set_lazy_imports_filter can make a lazy import eager. Such a module then fails at the import line.

Verified by test modules

  • test/recipes/test_type_checking_to_lazy.py

Implemented by code modules

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_BLOCKS holds the patterns. A new form of the block is a new pattern there.
  • _can_be_lazy decides which imports PEP 810 allows to be lazy.