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

Paul Moore p.f.moore at gmail.com
Wed Oct 30 12:52:13 CET 2013


On 30 October 2013 10:13, Oscar Benjamin <oscar.j.benjamin at gmail.com> wrote:
>> However, being able to write
>>
>>     last_n = s[-n:]
>>
>> is extremely useful.
>
> Until you hit the bug where n is 0.
>
>>>> a = 'abcde'
>>>> for n in reversed(range(4)):
> ...     print(n, a[-n:])
> ...
> 3 cde
> 2 de
> 1 e
> 0 abcde
>
> This is what I mean by the wraparound behaviour causing corner cases
> and bugs. I and others have reported that this is a bigger source of
> problems than the off-by-one negative stride issue which has never
> caused me any actual problems.

OK, fair enough. That has *never* been an issue to me, but nor have
negative strides. So I'm in the same boat as Tim, that I never need
any of this so I don't care how it's implemented :-)

What I do care about is that functionality that I do use (s[:-n] where
n is *not* zero) doesn't get removed because it leads to corner cases
that I don't hit but others do. Adding extra functionality with better
boundary conditions is one thing, removing something that people use
*a lot* without issue is different.

Most of my use cases tend to have constant n - something like "if
filename.endswith('.py'): filename = filename[:-3]". Here, using -2
(or -4, or 3j, or len(filename)-3, or whatever ends up being proposed)
isn't too hard, but it doesn't express the extent as clearly to me. Or
I calculate n based on something that means that n will never be 0
(typically some sort of "does this case apply" check like the endswith
above). And again, -n expresses my intent most clearly and won't
trigger bugs.

I'm not saying you don't have real-world use cases, and real bugs
caused by this behaviour, but I am suggesting that it only bites in
particular types of application.

Paul


More information about the Python-ideas mailing list