Python Glossary Русский

all Python 3astfunction

ast.iter_child_nodes()

helper functions

Iterates over the direct children of a node, one level down only. The building block for a hand-written recursive tree walk.

Syntax

for child in ast.iter_child_nodes(node): ...

Unlike walk, it does not descend further and does not yield the node itself. List fields (body, args) are flattened into separate nodes, while non-node fields (the id string of Name, the number in Constant.value) are skipped. Helper nodes such as Load() count as children too, so filter with isinstance.

Examples

import ast
node = ast.parse('a + 1', mode='eval').body
print([type(c).__name__ for c in ast.iter_child_nodes(node)])  # → ['Name', 'Add', 'Constant']
import ast
def depth(node):
    return 1 + max((depth(c) for c in ast.iter_child_nodes(node)), default=0)
print(depth(ast.parse('f(g(h(x)))', mode='eval')))  # → 6

See also

Open in the full glossarydocs.python.orgReport an inaccuracy