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.
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.
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().
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:
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)
The abstract grammar is currently defined as follows:
-- ASDL's five builtin types are identifier, int, string, bytes, objectmodule 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) | ClassDef(identifier name, expr* bases, keyword* keywords, expr? starargs, expr? kwargs, 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) | While(expr test, stmt* body, stmt* orelse) | If(expr test, stmt* body, stmt* orelse) | With(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 | 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, expr? starargs, expr? kwargs) | Num(object n) -- a number as a PyObject. | Str(string s) -- need to specify raw, unicode, etc? | Bytes(bytes s) | Ellipsis -- other literals? bools? -- 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 | 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, identifier? vararg, expr? varargannotation, arg* kwonlyargs, identifier? kwarg, expr? kwargannotation, expr* defaults, expr* kw_defaults) arg = (identifier arg, expr? annotation) -- keyword arguments supplied to call keyword = (identifier arg, expr value) -- import name with optional 'as' alias. alias = (identifier name, identifier? asname) withitem = (expr context_expr, expr? optional_vars)}Apart from the node classes,ast module defines these utility functionsand classes for traversing abstract syntax trees:
Parse the source into an AST node. Equivalent tocompile(source,filename,mode,ast.PyCF_ONLY_AST).
Safely evaluate an expression node or a string containing a Pythonexpression. The string or node provided may only consist of the followingPython literal structures: strings, bytes, numbers, tuples, lists, dicts,sets, booleans, andNone.
This can be used for safely evaluating strings containing Python expressionsfrom untrusted sources without the need to parse the values oneself.
Changed in version 3.2:Now allows bytes and set literals.
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().
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.
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.
Copy source location (lineno andcol_offset) fromold_nodetonew_node if possible, and returnnew_node.
Yield a tuple of(fieldname,value) for each field innode._fieldsthat is present onnode.
Yield all direct child nodes ofnode, that is, all fields that are nodesand all items of fields that are lists of nodes.
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.
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 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.
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.
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)
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.
31.1.parser — Access Python parse trees
31.3.symtable — Access to the compiler’s symbol tables
Enter search terms or a module, class or function name.