Python Glossary Русский

all Python 3astterm

ast.AST

root and base nodes

The base class of every syntax tree node: Module, expressions, statements and operators returned by ast.parse() all derive from it.

Syntax

class ast.AST; node._fields; node.lineno, node.col_offset

Nodes compare by identity, not by content: ast.parse('x') == ast.parse('x') is False, so compare trees through ast.dump() (or ast.compare() since 3.14). The field names of a node live in the class attribute _fields, while the lineno and col_offset positions exist on expressions, statements and some helper nodes (arg, keyword, alias, except handlers, patterns, type params) — operators such as Add have none. The repr() of a node changed in 3.14 (it now lists the fields), so tests should check specific fields rather than print a whole node.

Examples

import ast
tree = ast.parse('x + 1')
print(isinstance(tree, ast.AST))  # → True
print(ast.BinOp._fields)  # → ('left', 'op', 'right')
print(tree == ast.parse('x + 1'))  # → False — узлы сравниваются по идентичности
print(ast.dump(tree) == ast.dump(ast.parse('x + 1')))  # → True
import ast
node = ast.parse('a = 10').body[0]
print(node.lineno, node.col_offset, node.end_col_offset)  # → 1 0 6
print(hasattr(ast.Add(), 'lineno'))  # → False

See also

Open in the full glossarydocs.python.orgReport an inaccuracy