What is ast.For in Python?
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.
Parameters
targetcontains the variable(s) the loop assigns to, which can be aName,Tuple, orListnode.itercontains the item to be looped over as a single node.bodycontains lists of nodes to execute.orelsecontains lists of nodes to execute in a normal situation where there is nobreakstatement used in the loop.type_commentis an optional parameter with the type annotation as a comment.
Code
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)
Explanation
- We define a
ForVisitorclass that extends from the parent classast.NodeVisitor. We override the predefinedvisit_Forandvisit_Namemethods in the parent class, which receive theForandNamenodes, respectively. - In these methods, we print the type and the fields inside the node and call the
generic_visit()method to visit the children nodes of the input node. - We initialize a visitor object of the class
ForVisitor(line 14). - We write a loop and send it to the
ast.parse()method, which returns the result of the expression after evaluation, and then stores this result intree. - The
ast.dump()method returns a formatted string of the tree structure intree. You can observe the string returned by thedumpfunction 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 theparse()method. - The built-in
visitmethod available to thevisitorobject visits all the nodes in the tree structure.