On Tue, 21 Jun 2022 at 11:07, Rob Cliffe via Python-ideas <python-ideas@python.org> wrote:
On 20/06/2022 17:39, Jeremiah Paige wrote:
On Sat, Jun 18, 2022 at 5:42 PM Rob Cliffe via Python-ideas <python-ideas@python.org> wrote:
To me, the natural implementation of slicing on a non-reusable iterator (such as a generator) would be that you are not allowed to go backwards or even stand still: mygen[42] mygen[42] ValueError: Element 42 of iterator has already been used
I agree that indexing an iterator such that it could only go forward feels like a reasonable and useful feature in python, but I disagree about the ValueError. To me the above produces two values: the 43rd and 85th elements produced by mygen. Anything else is a bizarre error waiting to arise at obscure times. What if this iterator is passed to another function? Used in a loop? Now this information about what index has been used has to be carried around and checked on every access.
Oh, OK, I have no problem with that (except shouldn't it be the 43rd and 86th elements?). I guess which interpretation is more useful depends on the use case.
I think this confusion is exactly why arbitrary iterators shouldn't be indexable like this. Slicing them is a maybe, but even there, it's hard to explain that mygen[3..] is a destructive operation on mygen (rather than, as it is with sequences, a copy). It wouldn't be hard to create a "lazy caching sequence-like view" to an iterable, which would never reset its base index, but within the iterator itself, it's inevitably going to cause a lot of confusion. ChrisA