Python AST: How to get children from node

I am working on Python 2.6.5.

Given an abstract syntax tree, I want to get its children.

I was looking for a stack overflow, but to no avail. Most messages are found on ast.NodeVisitorand methods defined in it visit,generic_visit(). However, AFAIU, visit()and generic_visit()do not give us children, rather, they directly apply the function recursively on them

Can someone please write a short code or to demonstrate it? Is there a predefined function in the python library for the same?

Thank!

+3
source share
2 answers

, node, , node. node _fields, . ,

>>> ast.parse('5+a')
<_ast.Module object at 0x02C1F730>
>>> ast.parse('5+a').body
[<_ast.Expr object at 0x02C1FF50>]
>>> ast.parse('5+a').body[0]
<_ast.Expr object at 0x02C1FBF0>
>>> ast.parse('5+a').body[0]._fields
('value',)
>>> ast.parse('5+a').body[0].value
<_ast.BinOp object at 0x02C1FF90>
>>> ast.parse('5+a').body[0].value._fields
('left', 'op', 'right')
>>> ast.parse('5+a').body[0].value.left
<_ast.Num object at 0x02C1FB70>

..

, ,

, CPython

:

>>> type(ast.parse('5+a'))
<class '_ast.Module'>

, , . , , , .

>>> ast.parse('5+a')._fields
('body',)
>>> ast.parse('5+a').body
[<_ast.Expr object at 0x02E965B0>]

_fields AST - "", body - AST. , stmt, , Expr expr, value

>>> ast.parse('5+a').body[0].value
<_ast.BinOp object at 0x02E96330>

BinOp, , 3 , , . , .

+3

ast iter_child_nodes, .

def iter_child_nodes(node):                                                    
    """                                                                        
    Yield all direct child nodes of *node*, that is, all fields that are nodes 
    and all items of fields that are lists of nodes.                           
    """                                                                        
    for name, field in iter_fields(node):                                      
        if isinstance(field, AST):                                             
            yield field                                                        
        elif isinstance(field, list):                                          
            for item in field:                                                 
                if isinstance(item, AST):                                      
                    yield item                                                 

                                                                               `
+3

All Articles