What is ast.Continue in Python?

Abstract Syntax Tree

ast.Continue is a class defined in the ast module which expresses the continue statement 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 a continue statement, the ast.Continue class is invoked, which expresses the continue statement to a node in an ast tree data structure. The ast.Continue class represents the Continue node type in the ast tree.

Example

import ast
from pprint import pprint
class ContinueVisitor(ast.NodeVisitor):
def visit_If(self, node):
print('Node type: If\nFields:', node._fields)
ast.NodeVisitor.generic_visit(self, node)
def visit_Compare(self, node):
print('Node type: Compare\nFields:', node._fields)
ast.NodeVisitor.generic_visit(self, node)
def visit_Name(self, node):
print('Node type: Name\nFields:', node._fields)
ast.NodeVisitor.generic_visit(self, node)
def visit_Constant(self, node):
print('Node type: Constant\nFields:', node._fields)
ast.NodeVisitor.generic_visit(self, node)
def visit_Continue(self, node):
print('Node type: Continue\nFields:', node._fields)
ast.NodeVisitor.generic_visit(self, node)
visitor = ContinueVisitor()
tree = ast.parse("""
if x < 20:
continue
""")
pprint(ast.dump(tree))
visitor.visit(tree)

Explanation

  • We define a ContinueVisitor class that extends from the parent class ast.NodeVisitor. We override the predefined visit_If, visit_Compare, visit_Constant, visit_Name, and visit_Continue methods in the parent class, which receive the If, Compare, Constant, Name, and Continue nodes, respectively.
  • In the method, we print the type and the fields inside the node and call the generic_visit() method, which invokes the propagation of visit on the children nodes of the input node.
  • We initialize a visitor object of the class ContinueVisitor.
  • We write Python code that contains an if block with a continue statement. We pass the code to the ast.parse() method, which returns the result of the expression after evaluation, and store the result in a tree.
  • The ast.dump() method returns a formatted string of the tree structure in a tree.
  • The visit method available to the visitor object visits all the nodes in the tree structure.

Free Resources