Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


What is ast.For in Python?

Adnan Abbas

The ast (Abstract Syntax Tree)tree representation of source code module allows us to interact with Python code and modify it. Python comes with abstract syntax grammar, which is subject to change with every Python release. This module helps applications process trees of syntax and find out what the current syntax grammar looks like programmatically. Abstract syntax trees are great tools for program analysis and program transformation systems.


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 ast
from pprint import pprint

class ForVisitor(ast.NodeVisitor):
    def visit_For(self, node):
        print('Node type: For\nFields: ', node._fields)

    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:
Code example of ast.For


  • We define a 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.
  • 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 in tree.
  • The 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.
  • The built-in visit method available to the visitor object visits all the nodes in the tree structure.



View all Courses

Keep Exploring