Python Glossary Русский

all Python 3astterm

ast.Slice

expressions

Node for a slice lower:upper:step inside a Subscript; an omitted bound is stored as None.

Syntax

ast.Slice(lower=None, upper=None, step=None)

Slice appears only in the slice field of a Subscript (or inside a Tuple there); there is no standalone "1:2" expression in Python. An omitted bound and an explicit None differ: a[:] gives three None values, while a[None:] gives lower = Constant(None). Do not confuse it with the builtin slice(): calling slice(1, 2) is a plain Call, while the Slice node describes the colon syntax.

Examples

import ast
s = ast.parse('a[::2]', mode='eval').body.slice
print(type(s).__name__, s.lower, s.upper, s.step.value)  # → Slice None None 2
n = ast.parse('a[None:]', mode='eval').body.slice
print(type(n.lower).__name__)  # → Constant

See also

Open in the full glossarydocs.python.orgReport an inaccuracy