What is ast.Try(body, handlers, orelse, finalbody) in Python?

Abstract Syntax Tree

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

Class parameters

  • body: list of nodes in the body of each block.
  • orelse: list of nodes in the body of else nodes.
  • finalbody: list of nodes in the body of the finally node.
  • handlers: list of ExceptHandler nodes.

Code

import ast
from pprint import pprint
class TryVisitor(ast.NodeVisitor):
def visit_Try(self, node):
print('Node type: Try\nFields:', node._fields)
ast.NodeVisitor.generic_visit(self, node)
def visit_ExceptHandler(self, node):
print('Node type: ExceptHandler\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_Pass(self, node):
print('Node type: Pass\nFields:', node._fields)
ast.NodeVisitor.generic_visit(self, node)
visitor = TryVisitor()
tree = ast.parse("""
try:
pass
except Exception:
pass
else:
pass
finally:
pass
""")
pprint(ast.dump(tree))
visitor.visit(tree)

Explanation

  • We define a TryVisitor class that extends from the parent class ast.NodeVisitor. We override the predefined visit_Try, visit_ExceptHandler, visit_Name, and visit_Pass methods in the parent class, which receive the Try, ExceptHandler, Name, and Pass 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 TryVisitor.

  • We write Python code that contains a try and except block. We pass the code to the ast.parse() method, which returns the result of the expression after evaluation, and store the result in tree.

  • The ast.dump() method returns a formatted string of the tree structure in tree.

  • The visit method available to the visitor object visits all the nodes in the tree structure.

Free Resources