On May 10, 2020, at 02:42, Alex Hall firstname.lastname@example.org wrote:
- Handling negative indices for sequences (is there any reason we don't have that now?)
Presumably partly just to keep it minimal and simple. Itertools is all about transforming iterables into other iterables in as generic a way as possible. None of the other functions do anything special if given a more fully-featured iterable.
But also, negative indexing isn’t actually part of the Sequence protocol. (You don’t get negative indexes for free by inheriting Sequence as a mixin, nor is it ensured by testing isinstance with Sequence as an ABC.) It’s part of the extra stuff that list and the other builtin sequences happen to do. You didn’t suggest allowing negative islicing on set even though it could just as easily be implemented there, because you don’t expect negative indexing as part of the Set protocol (or the Sized Iterable protocol); you did expect it as part of the Sequence protocol, but Python’s model disagrees.
Maybe practicality beats purity here, and islice should take negative indices on any Sequence, or even Sized, input, even though that makes it different from other itertools functions, and ignores the fact that it could be simulating negative indexing on some types where it’s meaningless. But how often have you wanted to call islice with a negative index? How horrible is the workaround you had to write instead? I suspect that it’s already rare enough of a problem that it’s not worth it, and that any form of this proposal would make it even rarer, but I could be wrong.