On this page
ast
Prev: array | Up: stdlib_module | Next: asyncio
Rel: sys, sysconfig, builtins, warnings, dataclasses
Ref: docs.python.org — ast
Tags: #public #python3 #stdlib
Import
import ast
Overview
Parses Python source code into an Abstract Syntax Tree (AST) for static analysis, linting, refactoring, and safe literal evaluation (ast.literal_eval). Reach for ast whenever you need to inspect or transform Python syntax reliably without executing the code—never use regex to parse Python.
Quick Start
import ast
data = ast.literal_eval("{'a': [1, 2, 3], 'ok': True}")
assert data == {"a": [1, 2, 3], "ok": True}
tree = ast.parse("def greet(name: str) -> str:\n return f'Hi {name}'\n")
fn = tree.body[0]
assert isinstance(fn, ast.FunctionDef) and fn.name == "greet"
Implementation Walkthrough
1. Extracting Imports & Function Definitions with ast.NodeVisitor
import ast
class ImportCollector(ast.NodeVisitor):
def __init__(self) -> None:
self.modules: set[str] = set()
def visit_Import(self, node: ast.Import) -> None:
for alias in node.names:
self.modules.add(alias.name.split(".")[0])
def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
if node.module:
self.modules.add(node.module.split(".")[0])
tree = ast.parse("import os.path\nfrom pathlib import Path\n")
collector = ImportCollector()
collector.visit(tree)
assert collector.modules == {"os", "pathlib"}
2. Rewriting & Unparsing Source with NodeTransformer + ast.unparse()
import ast
class DoubleInts(ast.NodeTransformer):
def visit_Constant(self, node: ast.Constant) -> ast.AST:
if isinstance(node.value, int) and not isinstance(node.value, bool):
return ast.copy_location(ast.Constant(node.value * 2), node)
return node
tree = DoubleInts().visit(ast.parse("x = 3 + 4"))
ast.fix_missing_locations(tree)
assert ast.unparse(tree) == "x = 6 + 8"
Gotchas & Boundaries
ast.literal_eval()is safe for untrusted literals, NOT arbitrary expressions: It only accepts strings, bytes, numbers, tuples, lists, dicts, sets, booleans, andNone—and can still hit recursion limits on deeply nested input.ast.parse()drops comments and formatting: Use tokenize if you need exact whitespace or comments.- Call
ast.fix_missing_locations(tree)after modifying nodes before compiling the transformed AST. isinstance(True, int)isTruein Python: Checknot isinstance(val, bool)when filtering integerast.Constantnodes.
Common Functions
- ast.compare() —
compare(a, b, /, *, compare_attributes=False)— Recursively compares two ASTs. - ast.copy_location() —
copy_location(new_node, old_node)— Copy source location (lineno,col_offset,end_lineno, andend_col_offsetattributes) from old_node to new_node if possible, and return new_node. - ast.dump() —
dump(node, annotate_fields=True, include_attributes=False, *, indent=None, show_empty=False)— Return a formatted dump of the tree in node. This is mainly useful for debugging purposes. If annotate_fields is true (by default), the returned string will show the names and the values for fields. - ast.fix_missing_locations() —
fix_missing_locations(node)— When you compile a node tree with compile(), the compiler expects lineno and col_offset attributes for every node that supports them. This is rather tedious to fill in for generated nodes, so this helper adds these attributes - ast.get_docstring() —
get_docstring(node, clean=True)— Return the docstring for the given node or None if no docstring can be found. If the node provided does not have docstrings a TypeError will be raised. - ast.get_source_segment() —
get_source_segment(source, node, *, padded=False)— Get source code segment of the source that generated node. - ast.increment_lineno() —
increment_lineno(node, n=1)— Increment the line number and end line number of each node in the tree starting at node by n. This is useful to "move code" to a different location in a file. - ast.iter_child_nodes() —
iter_child_nodes(node)— Yield all direct child nodes of node, that is, all fields that are nodes and all items of fields that are lists of nodes. - ast.iter_fields() —
iter_fields(node)— Yield a tuple of(fieldname, value)for each field innode._fieldsthat is present on node. - ast.literal_eval() —
literal_eval(node_or_string)— Evaluate an expression node or a string containing only a Python expression. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, - ast.main() —
main(args=None)—ast.main()function. - ast.parse() —
parse(source, filename='<unknown>', mode='exec', *, type_comments=False, feature_version=None, optimize=-1)— Parse the source into an AST node. - ast.unparse() —
unparse(ast_obj)—ast.unparse()function. - ast.walk() —
walk(node)— Recursively yield all descendant nodes in the tree starting at node (including node itself), in no specified order. This is useful if you only want to modify nodes in place and don't care about the context.
Classes & Objects
- ast.Add — Add
- ast.alias — alias(identifier name, identifier? asname)
- ast.And — And
- ast.AnnAssign — AnnAssign(expr target, expr annotation, expr? value, int simple)
- ast.arg — arg(identifier arg, expr? annotation, string? type_comment)
- ast.arguments — arguments(arg* posonlyargs, arg* args, arg? vararg, arg* kwonlyargs, expr?* kw_defaults, arg? kwarg, expr* defaults)
- ast.Assert — Assert(expr test, expr? msg)
- ast.Assign — Assign(expr* targets, expr value, string? type_comment)
- ast.AST —
ast.ASTclass. - ast.AsyncFor — AsyncFor(expr target, expr iter, stmt* body, stmt* orelse, string? type_comment)
- ast.AsyncFunctionDef — AsyncFunctionDef(identifier name, arguments args, stmt* body, expr* decorator_list, expr? returns, string? type_comment, type_param* type_params)
- ast.AsyncWith — AsyncWith(withitem* items, stmt* body, string? type_comment)
- ast.Attribute — Attribute(expr value, identifier attr, expr_context ctx)
- ast.AugAssign — AugAssign(expr target, operator op, expr value)
- ast.AugLoad — Deprecated AST node class. Unused in Python 3.
- ast.AugStore — Deprecated AST node class. Unused in Python 3.
- ast.Await — Await(expr value)
- ast.BinOp — BinOp(expr left, operator op, expr right)
- ast.BitAnd — BitAnd
- ast.BitOr — BitOr
Constants & Attributes
ast.PyCF_ALLOW_TOP_LEVEL_AWAIT(int) =8192ast.PyCF_ONLY_AST(int) =1024ast.PyCF_OPTIMIZED_AST(int) =33792ast.PyCF_TYPE_COMMENTS(int) =4096
Linked from
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/array
- tuts/python3/stdlib_module/asyncio
- tuts/python3/stdlib_module/pyclbr
- tuts/python3/stdlib_module/stdlib_module
- tuts/python3/stdlib_module/symtable
- tuts/python3/stdlib_module/tokenize
- tuts/python3/tutorials/intermediate_python_and_software_engineering/type_hinting_and_static_analysis
Related notes
- tuts/python3/stdlib_module/array Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/asyncio Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/tokenize Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/ast/Add Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/ast/alias Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/ast/And Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/ast/AnnAssign Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/ast/arg Linked here; shared tags: #stdlib