all Python 3astterm
ast.expr_context
variables
The abstract class of a name's context: Load (read), Store (write), Del (delete). It is the ctx field of Name, Attribute, Subscript, List, Tuple, Starred.
Syntax
isinstance(node.ctx, ast.Store)
ctx tells assignment from reading without inspecting the parent: in a[i] = b the Subscript itself is Store, while a and i inside it are Load. Walking the tree by ctx easily finds every variable the program changes. The subclasses AugLoad, AugStore and Param still exist, but the parser has not produced them for years.
Examples
import ast
target = ast.parse('a[i] = b').body[0].targets[0]
print(type(target.ctx).__name__, type(target.value.ctx).__name__) # → Store Load
import ast
tree = ast.parse('x = 1\ny += x\ndel z')
for n in ast.walk(tree):
if isinstance(n, ast.Name):
print(n.id, type(n.ctx).__name__) # → x Store / y Store / z Del / x Load
See also
Open in the full glossarydocs.python.orgReport an inaccuracy