Python Glossary Русский

all Python 3astterm

ast.Load

variables

The read context in the ctx field of Name, Attribute, Subscript, List, Tuple and Starred: the value is fetched, not assigned or deleted.

Syntax

ast.Name(id, ctx=ast.Load())

The context type is the only thing telling a read of x from an assignment x = … in a Name node, so 'where is this variable used' checks isinstance(node.ctx, ast.Load). CPython hands the very same Load object to the whole tree, so never mutate a ctx. Before 3.13 a node built without ctx would not compile; since 3.13 ctx defaults to Load().

Examples

import ast
tree = ast.parse('x = x + 1')
names = [n for n in ast.walk(tree) if isinstance(n, ast.Name)]
print([(n.id, type(n.ctx).__name__) for n in names])  # → [('x', 'Store'), ('x', 'Load')]
import ast
a = ast.parse('a', mode='eval').body.ctx
b = ast.parse('b', mode='eval').body.ctx
print(a is b)  # → True — один общий объект

See also

Open in the full glossarydocs.python.orgReport an inaccuracy