all Python 3astterm
ast.With
control flow
Node for the with statement: items is a list of withitem nodes (the expression and an optional as target), body is the block.
Syntax
ast.With(items, body, type_comment=None)
Several managers on one line form a single With with several items, not nested nodes, while a nested with is a separate With in body, so the two spellings give different trees. The as target lives in optional_vars and is None when absent. async with is a different node, AsyncWith. Before Python 3.3 the fields were different (context_expr directly on With).
Examples
import ast
w = ast.parse('with open(p) as f, lock:\n pass').body[0]
print(type(w).__name__, len(w.items)) # → With 2
print(w.items[0].optional_vars.id, w.items[1].optional_vars) # → f None
See also
Open in the full glossarydocs.python.orgReport an inaccuracy