1

This question is a result of my python ast work.

I have a node in the ast and I want to obtain its children.

The ._field attribute gives the names of all the children of a node. However it is different for different node depending upon the syntax node.

for example if node is of type BinOp..then node._field will yield ('left','op', 'right')

Hence to access the children of node I have to use node.left, node.op and node.right

But I want to do it for any general node.

given any node if I use node._field it will give me a tupple. How do I use this tupple for obtaining the children. The node can be any general node. So I do not know what the tuple would be like beforehand.

examples in form of codes will be really nice! Thanks!

1 Answer 1

2

To iterate over the children of an arbitrary node, use ast.iter_child_nodes(). To iterate over the fields instead, use ast.iter_fields().

Sign up to request clarification or add additional context in comments.

3 Comments

Alternatively, use ast.NodeVisitor or ast.NodeTransformer to handle the tree traversal, and just implement the methods relevant to the nodes of interest.
thanks for your reply! i wrote the following code st=ast.parse('5+a') print ast.iter_child_nodes(st) ..... output was <generator object iter_child_nodes at 0xb763de8> the output instead should have been the child of it.. an ast.expr object
@Adwait: These functions are meant to iterate over, so try for child in ast.iter_child_nodes(st).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.