_imports2s module

exception pyflyby._imports2s.ImportAlreadyExistsError
pyflyby._imports2s.ImportPathForRelativeImportsCtx(codeblock)

Context manager that temporarily modifies sys.path so that relative imports for the given codeblock work as expected.

exception pyflyby._imports2s.LineNumberAmbiguousError
exception pyflyby._imports2s.LineNumberNotFoundError
exception pyflyby._imports2s.NoImportBlockError
class pyflyby._imports2s.SourceToSourceFileImportsTransformation(arg)
_create_import_block_from_group(group, lines, start_line, end_line)

Create an import block from a group of import statements.

Extracts the import lines from source text, creates a PythonBlock and transformation, and adds it to import_blocks (wrapped with line metadata).

Parameters:
  • group (list[ast.Import | ast.ImportFrom]) – Consecutive import AST nodes to extract.

  • lines (list[str]) – All source lines of the file (1-indexed via lines[lineno - 1]).

  • start_line (int) – First line number of the group (1-indexed).

  • end_line (int) – Last line number of the group, accounting for multiline imports.

Return type:

None

_extract_imports_from_statement(stmt)

Recursively extract imports from a statement’s body (e.g., FunctionDef, ClassDef).

Return type:

None

_extract_local_import_blocks()

Recursively extract import blocks from function and class bodies. This allows us to find and remove unused imports within functions/classes.

Return type:

None

_line_contains_import(line, imp)

Check if a line contains the given import statement.

Parse the line as an import statement and compare Import objects, rather than using string matching which is fragile with spacing.

Return type:

bool

_original_block_startpos: dict[int, int]
_remove_local_import_from_blocks(imp, lineno)

Remove a local import from the actual code blocks. This modifies the _output of blocks in self.blocks to remove the import line.

_remove_local_imports_from_output(output)

Post-process the output to remove local imports that have been deleted.

This is necessary because local imports are embedded in function bodies, which are stored in self.blocks as plain text. When we remove imports from local import blocks, we need to also remove those lines from the output.

Return type:

FileText

_removed_lines_per_block: defaultdict[int, int]
_split_semicolon_chained_imports(output)

Split semicolon-chained import statements into separate lines.

For local import blocks that have semicolon_suffixes (code after semicolons), replace those lines with the import on one line and the remaining code on the next.

Return type:

FileText

add_import(imp, lineno=inf)

Add the specified import. Picks an existing global import block to add to, or if none found, creates a new one near the beginning of the module.

Parameters:

lineno – Line before which to add the import. Inf means no constraint.

blocks: list[SourceToSourceImportBlockTransformation | SourceToSourceTransformation]
find_import_block_by_lineno(lineno)

Find the import block containing the given line number.

Handles both top-level and local (function/class) import blocks. For local imports wrapped in _LocalImportBlockWrapper, checks the original line range. For regular imports, checks the line number range.

Return type:

SourceToSourceImportBlockTransformation or _LocalImportBlockWrapper

import_blocks: list[SourceToSourceImportBlockTransformation | _LocalImportBlockWrapper]
insert_new_blocks_after_comments(blocks)
insert_new_import_block()

Adds a new empty imports block. It is added before the first non-comment statement. Intended to be used when the input contains no import blocks (before uses).

preprocess()
Return type:

None

pretty_print(params=None)
remove_import(imp, lineno)

Remove the given import.

select_import_block_by_closest_prefix_match(imp, max_lineno)

Heuristically pick an import block that imp “fits” best into. The selection is based on the block that contains the import with the longest common prefix.

Parameters:

max_lineno – Only return import blocks earlier than max_lineno.

Return type:

SourceToSourceImportBlockTransformation

tidy_local_imports: bool = False
class pyflyby._imports2s.SourceToSourceImportBlockTransformation(arg)
preprocess()
pretty_print(params=None)
class pyflyby._imports2s.SourceToSourceTransformation(arg)
_output: PythonBlock
preprocess()
pretty_print(params=None)
class pyflyby._imports2s.SourceToSourceTransformationBase(arg)
classmethod _from_source_code(codeblock)
input: PythonBlock
output(params=None)

Pretty-print and return as a PythonBlock.

Return type:

PythonBlock

preprocess()
pretty_print(params=None)
class pyflyby._imports2s._LocalImportBlockWrapper(transform, start_lineno, end_lineno=None, semicolon_suffixes=None)

Wrapper for import blocks found within function/class bodies. Preserves the original line number range since the block’s internal line numbers may not match the file’s line numbers.

This will be useful for tidy imports which only know how to handle top level import.

_id: str
_original_imports: set[Import]
_semicolon_suffixes: dict[int, str]
end_lineno: int
get_removed_imports()

Return the set of imports that have been removed from this block.

Return type:

set[Import]

start_lineno: int
transform: SourceToSourceImportBlockTransformation
pyflyby._imports2s._group_consecutive_imports(body)

Group consecutive import statements from an AST body.

Parameters:

body (list) – List of AST nodes from a function/class body

Returns:

List of groups, where each group is a list of consecutive import statements

Return type:

list[list]

pyflyby._imports2s._maybe_insert_pass(lines, idx, indent, lineno)

Insert a pass statement at idx when removing a line would leave a block-opener (a line ending with :) without a body.

After a line has been deleted at position idx, this function walks backwards to find the nearest non-empty preceding line. If that line ends with : (a compound-statement header such as def, class, if, etc.) and the next non-empty line after idx is at an equal or lower indentation level, the block body is gone and a pass statement is inserted at idx using indent spaces.

Parameters:
  • lines (list[str]) – Source lines of the block, already modified (the import line has been deleted before this call).

  • idx (int) – Index into lines where the deleted line used to be.

  • indent (int) – Column offset (number of leading spaces) of the deleted line, used to indent the inserted pass.

  • lineno (int) – Absolute line number in the file (used only for logging).

Return type:

None

pyflyby._imports2s.fix_unused_and_missing_imports(codeblock, add_missing=True, remove_unused='AUTOMATIC', add_mandatory=True, db=None, params=None, tidy_local_imports=False)

Check for unused and missing imports, and fix them automatically.

Also formats imports.

By default only top-level imports are tidied. Set tidy_local_imports=True to also remove unused imports inside function and class bodies.

Individual imports can be excluded from removal by adding # tidy-imports: ignore-import as a trailing comment. This is whitespace sentitive between and must be a single space after the #, and after the :

In the example below, m1 and m3 are unused, so are automatically removed. np was undefined, so an import numpy as np was automatically added.

>>> codeblock = PythonBlock(
...     'from foo import m1, m2, m3, m4\n'
...     'm2, m4, np.foo', filename="/tmp/foo.py")
>>> print(fix_unused_and_missing_imports(codeblock, add_mandatory=False))
[PYFLYBY] /tmp/foo.py: removed unused 'from foo import m1'
[PYFLYBY] /tmp/foo.py: removed unused 'from foo import m3'
[PYFLYBY] /tmp/foo.py: added 'import numpy as np'
import numpy as np
from foo import m2, m4
m2, m4, np.foo
Parameters:

tidy_local_imports (bool) – If True, also tidy imports within function and class bodies. Defaults to False.

Return type:

PythonBlock