32.2.ast — Abstract Syntax Trees

Source code:Lib/ast.py


Theast module helps Python applications to process trees of the Pythonabstract syntax grammar. The abstract syntax itself might change with eachPython release; this module helps to find out programmatically what the currentgrammar looks like.

An abstract syntax tree can be generated by passingast.PyCF_ONLY_AST asa flag to thecompile() built-in function, or using theparse()helper provided in this module. The result will be a tree of objects whoseclasses all inherit fromast.AST. An abstract syntax tree can becompiled into a Python code object using the built-incompile() function.

32.2.1. Node classes

classast.AST

This is the base of all AST node classes. The actual node classes arederived from theParser/Python.asdl file, which is reproducedbelow. They are defined in the_ast Cmodule and re-exported inast.

There is one class defined for each left-hand side symbol in the abstractgrammar (for example,ast.stmt orast.expr). In addition,there is one class defined for each constructor on the right-hand side; theseclasses inherit from the classes for the left-hand side trees. For example,ast.BinOp inherits fromast.expr. For production ruleswith alternatives (aka “sums”), the left-hand side class is abstract: onlyinstances of specific constructor nodes are ever created.

_fields

Each concrete class has an attribute_fields which gives the namesof 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.BinOpinstances have an attributeleft of typeast.expr.

If these attributes are marked as optional in the grammar (using aquestion mark), the value might beNone. If the attributes can havezero-or-more values (marked with an asterisk), the values are representedas Python lists. All possible attributes must be present and have validvalues when compiling an AST withcompile().

lineno
col_offset

Instances ofast.expr andast.stmt subclasses havelineno andcol_offset attributes. Thelineno isthe line number of source text (1-indexed so the first line is line 1) andthecol_offset is the UTF-8 byte offset of the first token thatgenerated the node. The UTF-8 offset is recorded because the parser usesUTF-8 internally.

The constructor of a classast.T parses its arguments as follows:

  • If there are positional arguments, there must be as many as there are itemsinT._fields; they will be assigned as attributes of these names.
  • If there are keyword arguments, they will set the attributes of the samenames to the given values.

For example, to create and populate anast.UnaryOp node, you coulduse

node=ast.UnaryOp()node.op=ast.USub()node.operand=ast.Num()node.operand.n=5node.operand.lineno=0node.operand.col_offset=0node.lineno=0node.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)

32.2.2. Abstract Grammar

The abstract grammar is currently defined as follows:

-- ASDL's six builtin types are identifier, int, string, bytes, object, singletonmodule Python{    mod = Module(stmt* body)        | Interactive(stmt* body)        | Expression(expr body)        -- not really an actual node but useful in Jython's typesystem.        | Suite(stmt* body)    stmt = FunctionDef(identifier name, arguments args,                       stmt* body, expr* decorator_list, expr? returns)          | AsyncFunctionDef(identifier name, arguments args,                             stmt* body, expr* decorator_list, expr? returns)          | ClassDef(identifier name,             expr* bases,             keyword* keywords,             stmt* body,             expr* decorator_list)          | Return(expr? value)          | Delete(expr* targets)          | Assign(expr* targets, expr value)          | AugAssign(expr target, operator op, expr value)          -- use 'orelse' because else is a keyword in target languages          | For(expr target, expr iter, stmt* body, stmt* orelse)          | AsyncFor(expr target, expr iter, stmt* body, stmt* orelse)          | While(expr test, stmt* body, stmt* orelse)          | If(expr test, stmt* body, stmt* orelse)          | With(withitem* items, stmt* body)          | AsyncWith(withitem* items, stmt* body)          | Raise(expr? exc, expr? cause)          | Try(stmt* body, excepthandler* handlers, stmt* orelse, stmt* finalbody)          | Assert(expr test, expr? msg)          | Import(alias* names)          | ImportFrom(identifier? module, alias* names, int? level)          | Global(identifier* names)          | Nonlocal(identifier* names)          | Expr(expr value)          | Pass | Break | Continue          -- XXX Jython will be different          -- col_offset is the byte offset in the utf8 string the parser uses          attributes (int lineno, int col_offset)          -- BoolOp() can use left & right?    expr = BoolOp(boolop op, expr* values)         | BinOp(expr left, operator op, expr right)         | UnaryOp(unaryop op, expr operand)         | Lambda(arguments args, expr body)         | IfExp(expr test, expr body, expr orelse)         | Dict(expr* keys, expr* values)         | Set(expr* elts)         | ListComp(expr elt, comprehension* generators)         | SetComp(expr elt, comprehension* generators)         | DictComp(expr key, expr value, comprehension* generators)         | GeneratorExp(expr elt, comprehension* generators)         -- the grammar constrains where yield expressions can occur         | Await(expr value)         | Yield(expr? value)         | YieldFrom(expr value)         -- need sequences for compare to distinguish between         -- x < 4 < 3 and (x < 4) < 3         | Compare(expr left, cmpop* ops, expr* comparators)         | Call(expr func, expr* args, keyword* keywords)         | Num(object n) -- a number as a PyObject.         | Str(string s) -- need to specify raw, unicode, etc?         | Bytes(bytes s)         | NameConstant(singleton value)         | Ellipsis         -- the following expression can appear in assignment context         | Attribute(expr value, identifier attr, expr_context ctx)         | Subscript(expr value, slice slice, expr_context ctx)         | Starred(expr value, expr_context ctx)         | Name(identifier id, expr_context ctx)         | List(expr* elts, expr_context ctx)         | Tuple(expr* elts, expr_context ctx)          -- col_offset is the byte offset in the utf8 string the parser uses          attributes (int lineno, int col_offset)    expr_context = Load | Store | Del | AugLoad | AugStore | Param    slice = Slice(expr? lower, expr? upper, expr? step)          | ExtSlice(slice* dims)          | Index(expr value)    boolop = And | Or    operator = Add | Sub | Mult | MatMult | Div | Mod | Pow | LShift                 | RShift | BitOr | BitXor | BitAnd | FloorDiv    unaryop = Invert | Not | UAdd | USub    cmpop = Eq | NotEq | Lt | LtE | Gt | GtE | Is | IsNot | In | NotIn    comprehension = (expr target, expr iter, expr* ifs)    excepthandler = ExceptHandler(expr? type, identifier? name, stmt* body)                    attributes (int lineno, int col_offset)    arguments = (arg* args, arg? vararg, arg* kwonlyargs, expr* kw_defaults,                 arg? kwarg, expr* defaults)    arg = (identifier arg, expr? annotation)           attributes (int lineno, int col_offset)    -- keyword arguments supplied to call (NULL identifier for **kwargs)    keyword = (identifier? arg, expr value)    -- import name with optional 'as' alias.    alias = (identifier name, identifier? asname)    withitem = (expr context_expr, expr? optional_vars)}

32.2.3.ast Helpers

Apart from the node classes, theast module defines these utility functionsand classes for traversing abstract syntax trees:

ast.parse(source,filename='<unknown>',mode='exec')

Parse the source into an AST node. Equivalent tocompile(source,filename,mode,ast.PyCF_ONLY_AST).

ast.literal_eval(node_or_string)

Safely evaluate an expression node or a string containing a Python literal orcontainer display. The string or node provided may only consist of thefollowing Python literal structures: strings, bytes, numbers, tuples, lists,dicts, sets, booleans, andNone.

This can be used for safely evaluating strings containing Python values fromuntrusted sources without the need to parse the values oneself. It is notcapable of evaluating arbitrarily complex expressions, for example involvingoperators or indexing.

Changed in version 3.2:Now allows bytes and set literals.

ast.get_docstring(node,clean=True)

Return the docstring of the givennode (which must be aFunctionDef,ClassDef orModule node), orNoneif it has no docstring. Ifclean is true, clean up the docstring’sindentation withinspect.cleandoc().

ast.fix_missing_locations(node)

When you compile a node tree withcompile(), the compiler expectslineno andcol_offset attributes for every node that supportsthem. This is rather tedious to fill in for generated nodes, so this helperadds these attributes recursively where not already set, by setting them tothe values of the parent node. It works recursively starting atnode.

ast.increment_lineno(node,n=1)

Increment the line number of each node in the tree starting atnode byn.This is useful to “move code” to a different location in a file.

ast.copy_location(new_node,old_node)

Copy source location (lineno andcol_offset) fromold_nodetonew_node if possible, and returnnew_node.

ast.iter_fields(node)

Yield a tuple of(fieldname,value) for each field innode._fieldsthat is present onnode.

ast.iter_child_nodes(node)

Yield all direct child nodes ofnode, that is, all fields that are nodesand all items of fields that are lists of nodes.

ast.walk(node)

Recursively yield all descendant nodes in the tree starting atnode(includingnode itself), in no specified order. This is useful if you onlywant to modify nodes in place and don’t care about the context.

classast.NodeVisitor

A node visitor base class that walks the abstract syntax tree and calls avisitor function for every node found. This function may return a valuewhich is forwarded by thevisit() method.

This class is meant to be subclassed, with the subclass adding visitormethods.

visit(node)

Visit a node. The default implementation calls the method calledself.visit_classname whereclassname is the name of the nodeclass, orgeneric_visit() if that method doesn’t exist.

generic_visit(node)

This visitor callsvisit() on all children of the node.

Note that child nodes of nodes that have a custom visitor method won’t bevisited unless the visitor callsgeneric_visit() or visits themitself.

Don’t use theNodeVisitor if you want to apply changes to nodesduring traversal. For this a special visitor exists(NodeTransformer) that allows modifications.

classast.NodeTransformer

ANodeVisitor subclass that walks the abstract syntax tree andallows modification of nodes.

TheNodeTransformer will walk the AST and use the return value ofthe visitor methods to replace or remove the old node. If the return valueof the visitor method isNone, the node will be removed from itslocation, otherwise it is replaced with the return value. The return valuemay be the original node in which case no replacement takes place.

Here is an example transformer that rewrites all occurrences of name lookups(foo) todata['foo']:

classRewriteName(NodeTransformer):defvisit_Name(self,node):returncopy_location(Subscript(value=Name(id='data',ctx=Load()),slice=Index(value=Str(s=node.id)),ctx=node.ctx),node)

Keep in mind that if the node you’re operating on has child nodes you musteither transform the child nodes yourself or call thegeneric_visit()method for the node first.

For nodes that were part of a collection of statements (that applies to allstatement nodes), the visitor may also return a list of nodes rather thanjust a single node.

Usually you use the transformer like this:

node=YourTransformer().visit(node)
ast.dump(node,annotate_fields=True,include_attributes=False)

Return a formatted dump of the tree innode. This is mainly useful fordebugging purposes. The returned string will show the names and the valuesfor fields. This makes the code impossible to evaluate, so if evaluation iswantedannotate_fields must be set toFalse. Attributes such as linenumbers and column offsets are not dumped by default. If this is wanted,include_attributes can be set toTrue.

See also

Green Tree Snakes, an external documentation resource, has gooddetails on working with Python ASTs.