The ast
ast.For
ast.For(target, iter, body, orelse, type_comment)
ast.For
is a class defined in the ast
module that expresses a for
loop in Python in the form of an Abstract Syntax Tree.
When the parse()
method of ast
is called on a Python source code that contains for
loops, the ast.For
class is invoked, which expresses the for
statement to a node in an ast
tree data structure. The ast.For
class represents the For
node type in the ast
tree.
target
contains the variable(s) the loop assigns to, which can be a Name
, Tuple
, or List
node.iter
contains the item to be looped over as a single node.body
contains lists of nodes to execute.orelse
contains lists of nodes to execute in a normal situation where there is no break
statement used in the loop.type_comment
is an optional parameter with the type annotation as a comment.The following Python code illustrates an example of the ast.For
class.
import astfrom pprint import pprintclass ForVisitor(ast.NodeVisitor):def visit_For(self, node):print('Node type: For\nFields: ', node._fields)self.generic_visit(node)def visit_Name(self,node):print('Node type: Name\nFields: ', node._fields)ast.NodeVisitor.generic_visit(self, node)visitor = ForVisitor()tree = ast.parse("""for x in y:...else:...""")pprint(ast.dump(tree))visitor.visit(tree)
ForVisitor
class that extends from the parent class ast.NodeVisitor
. We override the predefined visit_For
and visit_Name
methods in the parent class, which receive the For
and Name
nodes, respectively.generic_visit()
method to visit the children nodes of the input node.ForVisitor
(line 14).ast.parse()
method, which returns the result of the expression after evaluation, and then stores this result in tree
.ast.dump()
method returns a formatted string of the tree structure in tree
. You can observe the string returned by the dump
function in the output of the code. The output shows the parameter values that are passed as a result of the code that is passed to the parse()
method.visit
method available to the visitor
object visits all the nodes in the tree structure.