I am working on Python 2.6.5.
Given a Abstract Syntax Tree, I want to obtain its children.
Most StackOverflow posts discuss ast.NodeVisitor and the methods defined in it: visit(), generic_visit().
However, visit() and generic_visit() do not give the children, rather they directly apply the function recursively on them.
Can someone please write a short code or so to demonstrate it?
Does there exist a predefined function in python library for the same?
The attaributes containing the node’s children depend on the type of syntax the node represents. Every node class also has a special
_fieldsattribute, that lists the attribute names for the child nodes that class has. For instance,and so on.
Edit, to clarify what’s going on
Before going any further, take a glance at the CPython Abstract Grammar
Consider:
In fact, if you look at the grammar, the first production rule is for Module. It appears to take a sequence of statements, as an argument called body.
The
_fieldsattribute of the AST is just “body”, and the body attribute is a sequence of AST nodes. Back to the grammar, looking in the production rules forstmt, we see thatExprtakes a single expr, namedvalueIf we look up the definition for BinOp, we see that it takes 3 different arguments, left, op and right. You should be able to proceed from there, I hope.