Python Glossary Русский

Python 3.3+astterm

ast.withitem

control flow

The node for one context manager in a with: context_expr is the expression, optional_vars the target after as or None. The items list of With and AsyncWith.

Syntax

ast.withitem(context_expr, optional_vars=None)

with open(a) as f, open(b) as g is one With with two withitem nodes, not nested Withs. The target after as is an expression in Store context: usually a Name, but it may be a tuple (as (x, y)) or an attribute. A withitem has no positions of its own; only the With has.

Examples

import ast
w = ast.parse('with open(a) as f, lock:\n    pass').body[0]
for item in w.items:
    target = item.optional_vars.id if item.optional_vars else None
    print(ast.unparse(item.context_expr), target)  # → open(a) f / lock None
print(type(w.items[0].optional_vars.ctx).__name__)  # → Store

See also

Open in the full glossarydocs.python.orgReport an inaccuracy