all Python 3astterm
ast.For
control flow
The node of a for loop: the target, the iterable iter, the body, the else branch in orelse and type_comment.
Syntax
ast.For(target, iter, body, orelse, type_comment=None)
The loop's else branch lives in orelse and runs when the loop was not stopped by break — an empty list means there is no else. An unpacking target for i, x in … is a Tuple with the Store context. A loop written with async for is a different class, AsyncFor, which visit_For never sees; list comprehensions are not For either but comprehension nodes inside ListComp.
Examples
import ast
src = 'for i, x in enumerate(s):\n pass\nelse:\n done()'
node = ast.parse(src).body[0]
print(type(node.target).__name__, type(node.target.ctx).__name__) # → Tuple Store
print(node.iter.func.id, len(node.orelse)) # → enumerate 1
See also
Open in the full glossarydocs.python.orgReport an inaccuracy