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
(Apologies if I don't know the difference between an iterator and an iterable; y'all know what I mean.) You still get a useful feature that you didn't have before. Expecting a generator (or whatever) to cache some its values in case you wanted a slice of them opens up a huge can of worms and is surely best forgotten.  (100Gb generator anyone?)  Well, maybe caching ONE value (the last one accessed) is reasonable, so you could stand still but not go backwards.  But it's still adding overhead.
Best wishes
Rob Cliffe


On 09/06/2022 10:28, Stephen J. Turnbull wrote:
Mathew Elman writes:

  > would it not be possible to have slicing fallback to islice if
  > __iter__ is implemented and __geitem__ is not?

The syntax is well-defined, but the semantics are not.

Consider "g[101]; g[100]" for g a generator object.  This either
requires all generators to keep a cache that can become arbitrarily
large, or violate the intuition of indexing by raising an error there,
or violate the intuition of indexing by returning the 102nd element,
then the 202nd element (what "islice(g,101,102); islice(g,100,101)"
would do), or some API to tell the generator to disable the cache if
you don't need it, or maybe there's some other semantics you could
give it that will be undesirable for some people in some other way.

Any of those makes 100% sense to me in the abstract, but I'm pretty
sure if it's made into syntax I'll be 99% dissatisfied with it. :-)
Explicit is better than implicit in this case.

You could argue that islice should be made a builtin, but I don't know
that it's used enough to justify that.

_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/Y773Y7MRIYIVQP6NLSAIG3MLK25EL6WA/
Code of Conduct: http://python.org/psf/codeofconduct/

_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/6TYNAW25RTTH6G2YJKQ5MUHIEJ6Z5U6B/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to