refactorยถ
Refactoring Transformers Module.
This module provides transformers for refactoring Python code using LibCST. It includes functionality to rename functions, classes, and variables while preserving the code structure.
Example
>>> import libcst as cst
>>> from haive.tools.toolkits.dev.python.cst_toolkit.transformers.refactor import RenameTransformer
>>>
>>> # Read and parse source code
>>> with open("script.py", "f") as f:
>>> tree = cst.parse_module(f.read())
>>>
>>> # Create a rename mapping
>>> rename_map = {"old_function": "new_function", "OldClass": "NewClass"}
>>>
>>> # Apply transformations
>>> modified_tree = tree.visit(RenameTransformer(rename_map))
>>>
>>> # Write updated code back to file
>>> with open("script.py", "w") as f:
>>> f.write(modified_tree.code)
Classesยถ
Renames functions, classes, and variables in Python code. |
Module Contentsยถ
- class refactor.RenameTransformer(rename_map)ยถ
Bases:
libcst.CSTTransformer
Renames functions, classes, and variables in Python code.
This transformer finds and renames identifiers throughout the code based on a provided mapping, maintaining the structure and semantics of the original code.
- leave_ClassDef(original_node, updated_node)ยถ
Rename class definitions during the AST traversal.
- Parameters:
original_node (cst.ClassDef) โ The original class definition node
updated_node (cst.ClassDef) โ The updated class definition node
- Returns:
- The class definition with the updated name if itโs in
the rename map, otherwise the original node
- Return type:
cst.ClassDef
- leave_FunctionDef(original_node, updated_node)ยถ
Rename function definitions during the AST traversal.
- Parameters:
original_node (cst.FunctionDef) โ The original function definition node
updated_node (cst.FunctionDef) โ The updated function definition node
- Returns:
- The function definition with the updated name if itโs in
the rename map, otherwise the original node
- Return type:
cst.FunctionDef
- leave_Name(original_node, updated_node)ยถ
Rename variable and reference names during the AST traversal.
- Parameters:
original_node (cst.Name) โ The original name node
updated_node (cst.Name) โ The updated name node
- Returns:
- The name node with the updated value if itโs in
the rename map, otherwise the original node
- Return type:
cst.Name
- rename_mapยถ