line_profiler.autoprofile.profmod_extractor module

class line_profiler.autoprofile.profmod_extractor.ProfmodExtractor(tree: Module, script_file: str, prof_mod: list[str])[source]

Bases: object

Map prof_mod to imports in an abstract syntax tree.

Takes the paths and dotted paths in prod_mod and finds their respective imports in an abstract syntax tree.

Initializes the AST tree profiler instance with the AST, script file path and prof_mod

Parameters:
  • tree (_ast.Module) – abstract syntax tree to fetch imports from.

  • script_file (str) – path to script being profiled.

  • prof_mod (list[str]) – list of imports to profile in script. passing the path to script will profile the whole script. the objects can be specified using its dotted path or full path (if applicable).

extract_all() dict[tuple[str | int, ...], list[ImportTarget]][source]

Map prof_mod to imports in an abstract syntax tree. Takes the paths and dotted paths in prof_mod and finds their respective imports in an abstract syntax tree, returning their aliases and the location they appear in the AST.

Returns:

tree_imports_to_profile_dict (dict[tuple[str | int, …], list[ImportTarget]]);
dict of imports to profile
key (tuple[str | int, …]):

Location of the import statement in the AST; e.g. ('body', 0) for the case where it is the first statement in the ast.Module.body

value (list[ImportTarget]):

list of import targets, each with these attributes:

name (str):

Canonical name of the import

index (int):

Index where it occurs in e.g. a module body

alias (str | None):

Optional alias under which the import is inserted into the namespace

lineno (int | None):

Optional (1-indexed) line number associated with the target

resolved_name (str | None):

Name under which the import is inserted into the namespace (should never be :py:const`None` for non-star-imports)

Notes

  • As of now, from <module> import * is not supported, and will result in a UserWarning.

  • Nested imports (e.g. imports in try-except/if blocks) are not currently retrieved.

run() dict[int, str][source]

Deprecated, legacy method kept for backward compatibility.

Returns:

tree_imports_to_profile_dict (dict[int, str])
dict of top-level imports to profile
key (int):

index of import in module AST’s body

value (str):

alias (or name if no alias used) of the LAST target to import in the corresponding ast.Import or ast.ImportFrom statement

Notes

  • New code should use the extract_all() method, which handles multi-target import statements (see #434).

  • Calling this method issues a DeprecationWarning.

  • For multi-target import statements, this only preserves the last target. If this results in import targets being dropped, a UserWarning is issued.

  • from <module> import * is not supported, and will result in a UserWarning.

  • Nested imports (e.g. imports in try-except/if blocks) are not retrieved.