import_consolidator

Import Consolidator Module.

This module provides functionality to consolidate and deduplicate import statements in Python files using LibCST. It identifies duplicate imports and merges them into single, cleaner import statements.

Example

>>> from haive.tools.toolkits.dev.python.cst_toolkit.transformers.import_consolidator import clean_imports
>>> clean_imports("/path/to/file.py")

Classes

ImportConsolidator

Consolidates duplicate imports into a single statement.

Functions

clean_imports(filepath)

Merge duplicate imports in a Python file.

Module Contents

class import_consolidator.ImportConsolidator

Bases: libcst.CSTTransformer

Consolidates duplicate imports into a single statement.

This transformer tracks all import statements in a Python file and consolidates duplicates to reduce redundancy and improve code organization.

imports

Dictionary mapping module names to their alias (if any)

Type:

dict

leave_Module(original_node, updated_node)

Remove duplicates and consolidate imports at the module level.

Parameters:
  • original_node (cst.Module) – The original module node

  • updated_node (cst.Module) – The updated module node

Returns:

The module with consolidated import statements

Return type:

cst.Module

visit_Import(node)

Track module imports during the AST traversal.

Parameters:

node (cst.Import) – The import node being visited

imports
import_consolidator.clean_imports(filepath: str)

Merge duplicate imports in a Python file.

Reads a Python file, identifies duplicate imports, consolidates them, and writes the updated code back to the file.

Parameters:

filepath (str) – Path to the Python file to process

Raises:
  • FileNotFoundError – If the specified file does not exist

  • IOError – If there are issues reading from or writing to the file