What is the ast module _fields attribute of nodes in Python?
_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 astfrom pprint import pprintclass 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
TupleVisitorclass that extends from the parent classast.NodeVisitor. We override the predefinedvisit_Constantandvisit_Tuplemethods in the parent class, which receive theConstantandTuplenodes, respectively. - In the method, we print the type and the fields inside the node using the
node._fieldsattribute. - Then, we call the
generic_visit()method, which invokes the propagation of visits on the children nodes of the input node. - We initialize a
visitorobject of the classTupleVisitor. - We define a Python tuple
(2,4,6)and send it to theast.parse()method withmode='eval', which returns the result of the expression after evaluation, and store the result intree. - The
ast.dump()method returns a formatted string of the tree structure intree. - The
visitmethod available to thevisitorobjects visits all the nodes in the tree structure. - You can observe the output of
_fieldsof the Tuple and Constant nodes. The tuple node contains the children nodeseltsandctx. The constant node contains the children nodesvalueandkind.
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved