class ast.AST
This is the base of all AST node classes. The actual node classes are derived from the Parser/Python.asdl
file, which is reproduced below. They are defined in the _ast
C module and re-exported in ast
.
There is one class defined for each left-hand side symbol in the abstract grammar (for example, ast.stmt
or ast.expr
). In addition, there is one class defined for each constructor on the right-hand side; these classes inherit from the classes for the left-hand side trees. For example, ast.BinOp
inherits from ast.expr
. For production rules with alternatives (aka “sums”), the left-hand side class is abstract: only instances of specific constructor nodes are ever created.
-
_fields
-
Each concrete class has an attribute
_fields
which gives the names of all child nodes.Each instance of a concrete class has one attribute for each child node, of the type as defined in the grammar. For example,
ast.BinOp
instances have an attributeleft
of typeast.expr
.If these attributes are marked as optional in the grammar (using a question mark), the value might be
None
. If the attributes can have zero-or-more values (marked with an asterisk), the values are represented as Python lists. All possible attributes must be present and have valid values when compiling an AST withcompile()
.
-
lineno
-
col_offset
-
Instances of
ast.expr
andast.stmt
subclasses havelineno
andcol_offset
attributes. Thelineno
is the line number of source text (1-indexed so the first line is line 1) and thecol_offset
is the UTF-8 byte offset of the first token that generated the node. The UTF-8 offset is recorded because the parser uses UTF-8 internally.
The constructor of a class ast.T
parses its arguments as follows:
- If there are positional arguments, there must be as many as there are items in
T._fields
; they will be assigned as attributes of these names. - If there are keyword arguments, they will set the attributes of the same names to the given values.
For example, to create and populate an ast.UnaryOp
node, you could use
node = ast.UnaryOp() node.op = ast.USub() node.operand = ast.Num() node.operand.n = 5 node.operand.lineno = 0 node.operand.col_offset = 0 node.lineno = 0 node.col_offset = 0
or the more compact
node = ast.UnaryOp(ast.USub(), ast.Num(5, lineno=0, col_offset=0), lineno=0, col_offset=0)
Please login to continue.