Seek support for new slice syntax PEP.

Carl Banks pavlovevidence at gmail.com
Mon Dec 14 16:23:06 EST 2009


On Dec 14, 10:03 am, Dave <b49P23T... at stny.rr.com> wrote:
> Just as sets may now be written as {3,'hi'}, I propose that slices
> should be available using [start:end] syntax.  Following example comes
> from projecteuler.net problem 166.  The Numeric community would also
> like this, as would the general python user.  The slice notation would
> require one ":" between the brackets to differentiate it from a list,
> which is similar to the set notation requirement that disambiguates it
> from a dictionary.
>
> Several times now I've wanted python slice notation.  Perhaps I'll
> write a Python Enhancement Proposal.  I stored slices of vector array
> entries to add
>
> edge = 4
> indexes = []
> n = edge
> nn = n**2
> for i in range(edge):
>     indexes.extend([
>         slice(i*n,(i+1)*n,1),       # rows
>         slice(i,nn,n),              # cols
>         ])
>
> row_slices = indexes[0::2]
> col_slices = indexes[1::2]
> slash = slice(n-1,n*(n-1)+1,n-1)
> backslash = slice(0,nn,n+1)
>
> Which could have been written in a manner completely consistent with
> other python shorthand notations and for which python "cannot
> possibly" use the notation for some other purpose,
>
> edge = 4
> indexes = []
> n = edge
> nn = n**2
> for i in range(edge):
>     indexes.extend([
>         [i*n: (i+1)*n]                  # rows
>         [i: nn: n],                      # cols
>         ])
>
> row_slices = indexes[0::2]
> col_slices = indexes[1::2]
> slash = [n-1: n*(n-1)+1: n-1]
> backslash = [0: nn: n+1]

-1

Explicit creation of slice objects is an uncommon need and there is no
reason to support it with its own syntax.

I'd agree with Terry Reedy that range/xrange is far more commonly used
than slice objects, and if a floating slice syntax were ever added to
Python it ought to be used for range.


If you need to use a lot of slice objects you can lower your code
footprint by defining a helper class like this (adapt as needed):

class SliceCreator(object):
    def __getitem__(self,loc):
        if not isinstance(loc,slice):
            raise TypeError
        return loc
slc = SliceCreator()

slash = slc[n-1: n*(n-1)+1: n-1]


It might have been a reasonable idea for slice (and, perhaps, range)
to use slice notation rather than a function call, on the thinking
that the notational convenience outweighs the fact that you're not
actually getting an item, but it's too late for that.


Carl Banks



More information about the Python-list mailing list