Python ast Module
Example
Parse a simple statement and inspect the AST type:
import ast
tree = ast.parse("x = 1 + 2")
print(type(tree).__name__)
Try it Yourself »
Definition and Usage
The ast
module lets you parse Python source into an Abstract Syntax Tree (AST).
Use it to analyze, transform, or generate Python code programmatically, including safe evaluation of literals.
Members
Member | Description |
---|---|
AST | Base class for all nodes in the abstract syntax tree. |
copy_location() | Copy location info (line/column) from one node to another. |
dump() | Return a formatted string of the AST for debugging or inspection. |
fix_missing_locations() | Fill in missing location (line/column) information on nodes. |
get_docstring() | Return the docstring for a node, if present. |
get_source_segment() | Return the exact source substring that produced a node, if available. |
increment_lineno() | Increase the line numbers in a node and its children (e.g., when injecting code). |
iter_child_nodes() | Iterate over a node's direct child nodes. |
iter_fields() | Iterate over fields of an AST node. |
literal_eval() | Safely evaluate a string containing a Python literal structure. |
NodeTransformer | Visit and modify nodes in place; return a new node to replace the old one. |
NodeVisitor | Walk the tree and run visit_* methods for node types; no modifications. |
parse() | Parse Python source code into an AST tree. |
unparse() | Turn an AST back into Python source code. |
walk() | Recursively yield all nodes in the tree starting at a node. |