pyanalyze.ast_annotator

Functionality for annotating the AST of a module.

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

pyanalyze.ast_annotator.annotate_code(code: str, *, visitor_cls: ~typing.Type[~pyanalyze.name_check_visitor.NameCheckVisitor] = <class 'pyanalyze.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:
  • visitor_cls (Type[NameCheckVisitor]) – Pass a subclass of pyanalyze.name_check_visitor.NameCheckVisitor to customize pyanalyze behavior.

  • dump (bool) – If True, the annotated AST is printed out.

  • show_errors (bool) – If True, errors from pyanalyze are printed.

  • verbose (bool) – If True, more details are printed.

pyanalyze.ast_annotator.annotate_file(path: str | ~os.PathLike[str], *, visitor_cls: ~typing.Type[~pyanalyze.name_check_visitor.NameCheckVisitor] = <class 'pyanalyze.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:
  • visitor_cls (Type[NameCheckVisitor]) – Pass a subclass of pyanalyze.name_check_visitor.NameCheckVisitor to customize pyanalyze behavior.

  • dump (bool) – If True, the annotated AST is printed out.

  • show_errors (bool) – If True, errors from pyanalyze are printed.

  • verbose (bool) – If True, more details are printed.

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

Print an annotated AST in a readable format.