[Python-ideas] Where did we go wrong with negative stride?

Oscar Benjamin oscar.j.benjamin at gmail.com
Wed Oct 30 10:52:37 CET 2013


On 30 October 2013 07:39, Nick Coghlan <ncoghlan at gmail.com> wrote:
> On 30 October 2013 13:09, Ron Adam <ron3200 at gmail.com> wrote:
>> That's a lot of things to be trying to shove into one syntax!
>
> That's why I no longer think it should be handled as syntax. slice is
> a builtin, and keyword arguments are a thing.

I assume that you mean to add a reverse keyword argument to the slice
constructor so that I can do:

    b = a[slice(i, j, reverse=True)]

instead of

    b = a[i-1, j-1, -1]

or

    b = a[i:j][::-1]

Firstly would it not be better to add slice.__reversed__ so that it would be

    b = a[reversed(slice(i, j))]

Secondly I don't think I would ever actually want to use this over the
existing possibilities.

There are real problems with slicing and indexing in Python that lead
to corner cases and bugs but this particular issue is not one of them.
The real problems, including the motivating example at the start of
this thread, are caused by the use of negative indices to mean from
the end. Subtracting 1 from the indices when using a negative stride
isn't a big deal but correctly and robustly handling the wraparound
behaviour is. EAFP only works if invalid inputs raise an error and
this is very often not what happens with slicing and indexing.


Oscar


More information about the Python-ideas mailing list