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

Nick Coghlan ncoghlan at gmail.com
Wed Oct 30 02:34:00 CET 2013


On 30 October 2013 11:04, Andrew Barnert <abarnert at yahoo.com> wrote:
> On Oct 29, 2013, at 15:07, Nick Coghlan <ncoghlan at gmail.com> wrote:
>
> Isn't all that is needed to prevent the default wraparound behaviour
> clamping negative numbers to zero on input?
>
> As in:
>
> def clampleft(start, stop, step):
>     if start is not None and start < 0:
>         start = 0
>     if stop is not None and stop < 0:
>         stop = 0
>     return slice(start, stop, step)
>
> Except many of the wraparound cases people complain about are the other way
> around, negative stop wrapping around to 0.
>
> You could fix that almost as easily:
>
> def clampright(start, stop, step):
>     if start >= 0:
>         start = ???
>     if stop >= 0:
>         stop = None
>     return slice(start, stop, step)
>
> Except... What do you set start to if you want to make sure it's past-end?
> You could force an empty slice (which is the main thing you want) with,
> e.g., stop=start=0; is that close enough?

Yes, that's what I did in the rslice recipe - if it figured out an
empty slice was needed when explicit bounds were involved, it always
returned "slice(0, 0, step)" regardless of the original inputs.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list