pycroscope.ast_annotator

Functionality for annotating the AST of a module.

The APIs in this module use pycroscope’s type inference to annotate an AST with inferred pycroscope.value.Value objects in .inferred_value attributes.

pycroscope.ast_annotator.annotate_code(code: str, *, visitor_cls: type[~pycroscope.name_check_visitor.NameCheckVisitor] = <class 'pycroscope.name_check_visitor.NameCheckVisitor'>, dump: bool = False, show_errors: bool = False, verbose: bool = False) Module

Annotate a piece of Python code. Return an AST with extra inferred_value attributes.

Example usage:

tree = annotate_code("a = 1")
print(tree.body[0].targets[0].inferred_value)  # Literal[1]

This will import and exec() the provided code. If this fails, the code will still be annotated but the quality of the annotations will be much lower.

Parameters:
pycroscope.ast_annotator.annotate_file(path: str | ~os.PathLike[str], *, visitor_cls: type[~pycroscope.name_check_visitor.NameCheckVisitor] = <class 'pycroscope.name_check_visitor.NameCheckVisitor'>, verbose: bool = False, dump: bool = False, show_errors: bool = False) AST

Annotate the code in a Python source file. Return an AST with extra inferred_value attributes.

Example usage:

tree = annotate_file("/some/file.py")
print(tree.body[0].targets[0].inferred_value)  # Literal[1]

This will import and exec() the provided code. If this fails, the code will still be annotated but the quality of the annotations will be much lower.

Parameters:
pycroscope.ast_annotator.dump_annotated_code(node: AST, depth: int = 0, field_name: str | None = None) None

Print an annotated AST in a readable format.