Search code examples
pythonabstract-syntax-treeinternals

What syntax is represented by an ExtSlice node in Python's AST?


I'm wading through Python's ast module and can't figure out the slices definition:

slice = Ellipsis | Slice(expr? lower, expr? upper, expr? step) 
                 | ExtSlice(slice* dims) 
                 | Index(expr value) 

So far, I know that Ellipsis is [...], Slice is the usual [start:end:step] notation, Index is [index], but which notation is ExtSlice?


Solution

  • An extended slice is a slice with multiple parts which uses some slice-specific feature.

    A slice specific feature is something like ... (a literal ellipsis) or a : (a test separator).

    So, an example where ExtSlice is involved for an expression like o[...:None] or o[1,2:3].

    Here are some examples demonstrating this:

    >>> compile('o[x]', '<string>', 'exec', PyCF_ONLY_AST).body[0].value.slice
    <_ast.Index object at 0xb72a9e6c>
    >>> compile('o[x,y]', '<string>', 'exec', PyCF_ONLY_AST).body[0].value.slice
    <_ast.Index object at 0xb72a9dac>
    >>> compile('o[x:y]', '<string>', 'exec', PyCF_ONLY_AST).body[0].value.slice
    <_ast.Slice object at 0xb72a9dcc>
    >>> compile('o[x:y,z]', '<string>', 'exec', PyCF_ONLY_AST).body[0].value.slice
    <_ast.ExtSlice object at 0xb72a9f0c>
    >>>