What is ast.Continue in Python?
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 astfrom pprint import pprintclass 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
ContinueVisitorclass that extends from the parent classast.NodeVisitor. We override the predefinedvisit_If,visit_Compare,visit_Constant,visit_Name, andvisit_Continuemethods in the parent class, which receive theIf,Compare,Constant,Name, andContinuenodes, respectively. - In the method, we print the type and the fields inside the node and call the
generic_visit()method, which invokes the propagation ofvisiton the children nodes of the input node. - We initialize a visitor object of the class
ContinueVisitor. - We write Python code that contains an
ifblock with acontinuestatement. We pass the code to theast.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
visitmethod available to the visitor object visits all the nodes in the tree structure.