Python Glossary Русский

all Python 3astfunction

ast.iter_fields()

helper functions

Iterates over (field name, value) pairs of a node in _fields order. Lets you handle any node without knowing its class in advance.

Syntax

for name, value in ast.iter_fields(node): ...

The value can be anything: another node, a list of nodes, a string, a number or None, so check the type before descending. Position attributes (lineno, col_offset) are not fields and never show up here; they are listed in _attributes. Child nodes are easier to get with iter_child_nodes; iter_fields is for when field names matter too.

Examples

import ast
node = ast.parse('a + 1', mode='eval').body
for name, value in ast.iter_fields(node):
    print(name, type(value).__name__)  # → left Name / op Add / right Constant

See also

Open in the full glossarydocs.python.orgReport an inaccuracy