Refactoring recipes¶
{ #codemod-recipes }
Stable ID: CODEMOD-RECIPES
Responsibility¶
Recipes are PythonRefactoring subclasses that rewrite one Python file at a time, for gaps ruff does not fully or
safely cover. This page covers TypeParameterCheck and PrivateTypeParameterCheck, the recipes behind
Type parameter modernization, and TypeCheckingToLazy, the
recipe behind TYPE_CHECKING to lazy imports. The feature
pages describe what they change and refuse; this page says where it is decided.
Location¶
src/renaissance/recipes/type_parameter_check.py: theTypeParameterCheckpipeline and the edits its phases write.src/renaissance/recipes/type_parameter_rules.py: the reasons a type parameter is left unconverted, and the refusal rules.src/renaissance/recipes/type_parameter_declarations.py: reads and rewrites a declaration (T = TypeVar(...)).src/renaissance/recipes/type_parameter_localization.py: decides which imported type parameters get a local declaration, and the imports and text that replace them.src/renaissance/recipes/type_parameter_uses.py: finds where a declared name is used.src/renaissance/recipes/private_type_parameter_check.py:PrivateTypeParameterCheck, which drops the leading underscore from the type parameters of functions and classes and from every use they bind.src/renaissance/recipes/type_checking_to_lazy.py:TypeCheckingToLazy, which replaces module-levelif TYPE_CHECKING:import blocks by lazy imports.src/renaissance/recipes/step_runner.py:Step/run_steps, runs fix actions in order and commits only the ones that fixed something.src/renaissance/recipes/python_refactoring.py: the base class.typed_rootgives the root node as the recipe's node class.src/renaissance/utils/import_resolution.py: the import statements of a module and what they bind, the resolution offrom X import Yto a project file, the re-anchoring of a relative import on another file, andProjectImportGraph, the names each project file imports from the others.src/renaissance/utils/cst_utils.py: a module's top-level statements, the names they read or bind and the comment trailing a statement's line.src/renaissance/utils/ruff_utils.py:run_ruff_import_cleanup(ruff check --fix --select F401,I001) andrun_ruff_format(ruff format), which the CLI runs on the changed files.src/rejuvenation/migration_type_recipes.py: the CLI. It sets the recipe attributes, orders and repeats the files withProjectImportGraph, runs theruffstep and writes the report.
Public entry points¶
-
TypeParameterCheck.check()(andrun()) runs the three phases throughrun_steps, committing to disk between them. Each phase returns{name: "fixed" | "unsafe"}and records theUnsafeReasonof each unsafe name:Phase Step label Reasons attribute localize_imported_typevars()cross_filecross_file_unsafe_reasonsconvert_declared_typevars()convertedconverted_unsafe_reasonsremove_orphaned_declarations()orphanedorphaned_unsafe_reasonsconverted_unsafe_reasonscan also hold a fixed name that a generic class still uses (USED_IN_GENERIC_CLASS). -
type_param_kindsmaps each type parameter name the phases see to"TypeVar","ParamSpec"or"TypeVarTuple". -
The CLI sets these attributes before
check():Attribute Value min_python--pyproject_root<path>, or the file's folder for a single fileproject_wide_imported_namesProjectImportGraph.imported_namesof the fileignore_localize_originsthe absolute paths of the --ignorefileslocalize_importsFalsewith--no-localizationignored_namesthen holds the names this file imports from those files, or from any project file whenlocalize_importsisFalse. -
PythonRefactoring.process("TypeParameterCheck", file), used bycli.py refactor, sets none of these attributes.min_pythonstaysMIN_SUPPORTED_PYTHON, so adefault=is refused, andproject_wide_imported_namesstays empty, so a declaration that other files import is removed. -
PrivateTypeParameterCheck.check()(andrun()) renames each private type parameter and returns{old name: "fixed" | "unsafe"}. A name refused in any declaration is"unsafe".unsafe_reasonsholds the reason of each unsafe name, andtype_param_kindsthe kind of each name. The CLI runs it afterTypeParameterCheck, as steprenamed. -
TypeCheckingToLazy.run()rewrites every eligible block and commits. It is run withcli.py refactor.
Internal structure¶
Common¶
- Both type parameter recipes use the CST backend (
PythonRefactoring[PythonCstNode]) and read the tree throughtyped_root. Each edit replaces only the node it changes, so formatting and comments elsewhere are kept. uses_oftakes a declaration's uses from libcst's scope analysis (referenced_by). A use inside a string annotation orcast("T", x)counts. ATthat a PEP 695 type parameter of an enclosing function or class declares does not.- Files are read with universal newlines, and a modified file is written back with LF, also on the lines the recipe did not change. A file the recipe does not modify is not rewritten.
Refusals¶
is_safe_to_remove, is_safe_to_localize and conversion_refusal return an UnsafeReason or None. Each reason has
a message in UNSAFE_RULES, which the report prints; the report links DOCS_BASE_URL once.
| Reason | Decided by |
|---|---|
NO_PEP695_EQUIVALENT |
CONVERSION_RULES |
PEP696_VERSION_GATE |
CONVERSION_RULES |
DECLARED_TYPEVAR_EXPORTED |
REMOVAL_RULES |
IMPORTED_ELSEWHERE_IN_PROJECT |
REMOVAL_RULES |
ORIGIN_IMPORTS_CONSTRUCTOR_CONDITIONALLY |
LOCALIZATION_RULES |
SHARES_FUNCTION_WITH_UNCONVERTIBLE |
convert_declared_typevars |
USED_IN_GENERIC_CLASS |
convert_declared_typevars |
NAME_NOT_AT_MODULE_LEVEL |
plan_localizations |
NEW_NAME_NOT_FREE |
PrivateTypeParameterCheck._plan_renames |
USE_NOT_RENAMEABLE |
PrivateTypeParameterCheck._plan_renames |
In a rules tuple, the first rule that refuses decides the reason. Commenting out an entry switches its rule off, after which the recipe can write code that fails or breaks the files that import the name.
Conversion¶
- The CLI rejects
--pybelowMIN_SUPPORTED_PYTHON = (3, 12); the recipe itself does not check it.conversion_refusalcomparesmin_pythonwithPEP_696_MINIMUM = (3, 13)for adefault=. - A keyword outside
_CONVERTIBLE_KEYWORDSis refused (NO_PEP695_EQUIVALENT) instead of dropped.covariantandcontravariant(onTypeVarandParamSpec) andinfer_varianceare dropped, because a function's type parameter has no variance. Converting classes would have to refuse them. - A legacy type parameter belongs to the function whose signature uses it.
signature_functionfinds the functions whose parameter or return annotations use the name, andowning_functiongives each use to the outermost of them. A use outside every such signature, such asy: list[T] = []in a function whose signature does not useT, goes to no function. - Functions inside a class with the name in a base (
generic_classes) are skipped. - A function using a declaration that
conversion_refusalrejects gets none of its type parameters, since PEP 695 forbids mixing them with legacy ones. All refusals are therefore collected (_plan_conversions) before any parameter is added. _add_type_paramsreplaces only the function's name (f→f[T]) or its existing bracket, never the body. All type parameters of a function go into onereplace(), in declaration order with the defaulted ones last (type_params_bracket), since two edits on one node conflict.type_param_textwrites each parameter (T: int,**P,*Ts,= default) from the declaration's own text.
Removal¶
A declaration with no uses left (uses_of is empty) is orphaned and removed, unless REMOVAL_RULES refuses.
Conversion skips orphaned names too.
Localization¶
- The origin is parsed with
libcst.parse_module, and its declaration is copied as written, with the comment trailing it when it is alone on its line (declaration_text). All names localized from one import statement are handled together. NAME_NOT_AT_MODULE_LEVELis returned when the origin binds a name the arguments use (declaration_argument_names) only inside a block, or this file binds it to something else (from_import_sources).- A name the origin imports, such as the constructor, is imported here from the same module, with its alias
(
from_import_binding).rebase_relative_modulere-anchors a relative import of the origin on this file. A name the origin defines itself, or one whose module this file cannot name, is imported from the origin. - The import a localization replaces is this file's binding, so
is_safe_to_removechecks it too. OnlyDECLARED_TYPEVAR_EXPORTEDcan refuse there, since the planner gets noproject_wide_imported_names. - An import whose names are now declared locally is narrowed, keeping its comments, or dropped with its trailing
comment. The needed imports, once each, and then the declarations go after the last import that stays, so no import
ends up below code (E402). If every import is dropped, they replace the last dropped import line (
_anchor_index). They go where the replaced import was when it is dropped from a line with other statements, or when a statement between it and the last import reads one of its names. Merging, sorting and removing unused imports is left to the CLI'sruffstep.
Processing order¶
The CLI reads the imports of every file, --ignore files included, into a ProjectImportGraph. It processes origins
before the files importing from them (processing_order); the files of an import cycle form one group. After each
file, the graph reads its imports again, and a file is processed again (_merge_reports) while the names the project
imports from it change. A re-export through pkg/__init__.py is localized there first, so its importers copy it from
that file.
Private type parameters¶
PrivateTypeParameterCheck finds the type parameters of every def, async def and class, nested ones included,
with _DECLARATION_PATTERNS on an RST parse of the same text. It maps each one to its libcst node by offset and takes
its uses from referenced_by, so a module-level _T of the same name is left alone. A name inside a string annotation
is renamed inside the string. NEW_NAME_NOT_FREE refuses a new name that is not a valid identifier (_, _1), is
already a name in the function or class, or would appear twice in its bracket. USE_NOT_RENAMEABLE refuses a use that
is neither a name nor a single string.
Lazy imports¶
TypeCheckingToLazy uses the RST backend. TYPE_CHECKING_BLOCKS holds if TYPE_CHECKING:,
if typing.TYPE_CHECKING: and if False: with a $$includes body, matched against the module's statements without
recursion. A pattern without else does not match an if with one. _can_be_lazy checks the ast node of each
statement captured by $$includes, since a pattern cannot restrict the statements a $$ placeholder captures. It
accepts every import, except star and __future__ ones, and a block is rewritten when all its statements are accepted.
replace puts the captured statements in place of the if, with include_comments=False so the comment above it
stays, and with _make_lazy as the transform of $$includes.
Related features¶
Related concepts¶
Validated by test modules¶
See Verified by test modules in Type parameter modernization and TYPE_CHECKING to lazy imports.
Extension points¶
- A new recipe is a
PythonRefactoringsubclass in a module named after the class insnake_case, insrc/renaissance/recipes/.cli.py refactorfinds it by name. A CST recipe subclassesPythonRefactoring[PythonCstNode]and reads the tree throughtyped_root. - A new declaring constructor: add it to
_CONSTRUCTORSand_CONVERTIBLE_KEYWORDS, and write its syntax intype_param_text, all intype_parameter_declarations.py. - A keyword added by a later Python, or future PEP 695 syntax for variance or a bound on
**P/*Ts: add it to_CONVERTIBLE_KEYWORDSand carry it over intype_param_text. - A new refusal rule: add an
UnsafeReasonmember, a check function, aRefusalRuleentry in the stage's tuple and anUnsafeRulemessage inUNSAFE_RULES, all intype_parameter_rules.py, and a section on the feature page. - A new version gate compares
min_pythonwith a constant holding the minimum Python from the syntax's own PEP, asPEP_696_MINIMUMdoes. - A namespace package (PEP 420) as an import's origin: extend
resolve_project_module. Step/run_stepsis generic and can be reused by any recipe.
Non-goals¶
The feature page shows what each case does to the user's code, mostly under Known limitations.
- Every file is parsed and analysed, with no caching. An origin is parsed once per importing statement, and a file is processed again while the names imported from it change.
- The target's minimum Python is not read from
requires-python;--pysetsmin_python. - Renamed imports (
from shapes import T as U) and imports inside blocks are not localized (_Planner.runreads only top-levelfromimports). - A file importing with
from origin import *is not an importer:imported_project_namesrecords"*", so the origin's declaration is removed once the origin itself no longer uses it. - Only declarations in the file can block a function. A legacy type parameter that stays imported, such as
typing.AnyStr, does not, so the function mixes both syntaxes. __all__.extend(...)and__all__.append(...)are not read by_is_exported.- Only
__all__marks a declaration as public. One that nothing in the project uses is removed, even if other projects import it;--ignorekeeps such a file. - A name used only in the string value of a
TypeAliasis not a use foruses_of, so its declaration is removed. Unpack[Ts]→*Tsis left toruff'sUP044, see Rejected recipes.- A statement on the same line as a removed declaration or a replaced import (
T = TypeVar("T"); x = 1) is written back wrongly, a syntax error.ruff'sE702flags such lines. - Without the
ruffstep (--no-ruff, or the recipe used as a library), the added imports are not merged or sorted. - A decorator or a parameter default that reads
Tis evaluated outside the new type parameter's scope, but libcst places it inside, so the declaration looks unused and is removed. - Declarations that break the naming rule of PEP 484 (
T = U = TypeVar("T"),V = TypeVar("W"),TypeVar(name)) are not handled.ruff'sPLC0132flags a mismatched name. - A constructor from
from typing import *is not imported with the copy (ctor_source is None). - A
default=that names another declaration is carried over as is, sodef f[U = T]can still mean the module-levelT. - A constructor written with its module (
typing.TypeVar) is not recognised by_is_type_param_call. - Absolute imports are resolved from
<path>, so in asrc/layout run on the repository root,from pkg.shapes import Tdoes not findsrc/pkg/shapes.py.
Need to fix¶
Temporary list of defects the code should fix, with their issue where one exists. Each entry moves out once it is fixed or accepted as a non-goal.
- The comment lines above a localized declaration are not copied, because the rewriter handles a comment as one line (issue 189).
- An existing type parameter bracket on a converted function is rebuilt on one line, losing its comments and line
breaks (
_add_type_params, issue 279). - A localized declaration whose constructor this file already imports from another module adds a second import that shadows the first (issue 279).
- A file that starts with a UTF-8 byte order mark is corrupted:
def identity(x: T) -> T:becomesdef ideidentity[T] T) -> T:(issue 153). PrivateTypeParameterCheck.check()marks a name"unsafe"for the whole file when one declaration of it is refused.def ok[_T]then keeps its underscore because another function's_Tis refused, unless another name in the file is renamed:run_stepscommits every planned edit, andokis renamed while the report lists_Tonly for review.- The
ruffstep runs in the CLI's working directory and hides its output (ruff_utils.py). A project without aruffconfiguration gets the one of that directory, and a missing or failingruffgives no message. _report_generic_class_leftoversaddsUSED_IN_GENERIC_CLASSto a name that was converted in a standalone function, so the message "only used inside a class that is generic over it" is wrong there.- Type parameters of a
typestatement (type A[_T] = list[_T]) are neither renamed nor reported. T = U = TypeVar("T")leavesUundefined, andV = TypeVar("W")writesdef f[W](x: V) -> V, both without a warning.- The report writes "1 files" and "1 errors", and the reasons table counts names where the commit message counts files.