Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python

What is the ast module _fields attribute of nodes in Python?

Abdul Monum

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Abstract Syntax Tree

_fields is an attribute of each concrete node class of the ast module that provides the names of all child nodes of that node. Each concrete node class has at least the type attribute of their child nodes, which the output of _fields contains.

import ast
from pprint import pprint
class TupleVisitor(ast.NodeVisitor):
def visit_Tuple(self,node):
print('Node type: Tuple\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)
visitor = TupleVisitor()
tree = ast.parse('(2,4,6)', mode='eval')
pprint(ast.dump(tree))
visitor.visit(tree)

Explanation

  • We define a TupleVisitor class that extends from the parent class ast.NodeVisitor. We override the predefined visit_Constant and visit_Tuple methods in the parent class, which receive the Constant and Tuple nodes, respectively.
  • In the method, we print the type and the fields inside the node using the node._fields attribute.
  • Then, we call the generic_visit() method, which invokes the propagation of visits on the children nodes of the input node.
  • We initialize a visitor object of the class TupleVisitor.
  • We define a Python tuple (2,4,6) and send it to the ast.parse() method with mode='eval', 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 objects visits all the nodes in the tree structure.
  • You can observe the output of _fields of the Tuple and Constant nodes. The tuple node contains the children nodes elts and ctx. The constant node contains the children nodes value and kind.

RELATED TAGS

python

CONTRIBUTOR

Abdul Monum
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring