Python Glossary Русский

all Python 3astterm

ast.Subscript

expressions

Node for subscription value[slice]: value is what is indexed, slice is the index, a Slice or a tuple, ctx is Load, Store or Del.

Syntax

ast.Subscript(value, slice, ctx=ast.Load())

Since Python 3.9 the slice field holds the expression itself: the Index and ExtSlice wrappers belong to older versions, and code reading node.slice.value is broken. With several indices d[1, 2:3] the slice is a Tuple of Constant and Slice. Annotations like list[int] and dict[str, int] are Subscript too, so "find all indexing" without a filter also hits type hints.

Examples

import ast
s = ast.parse('a[0] = d[1, 2:3]').body[0]
print(type(s.targets[0]).__name__, type(s.targets[0].ctx).__name__)  # → Subscript Store
print([type(e).__name__ for e in s.value.slice.elts])  # → ['Constant', 'Slice']
import ast
ann = ast.parse('x: list[int]').body[0].annotation
print(type(ann).__name__, ann.value.id, ann.slice.id)  # → Subscript list int

See also

Open in the full glossarydocs.python.orgReport an inaccuracy