_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)
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.

find_import_block_by_lineno(lineno)

Find the import block containing the given line number.

Return type:

SourceToSourceImportBlockTransformation

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()
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

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)
pyflyby._imports2s.fix_unused_and_missing_imports(codeblock, add_missing=True, remove_unused='AUTOMATIC', add_mandatory=True, db=None, params=None)

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

Also formats imports.

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
Return type:

PythonBlock