On Tue, Nov 17, 2020 at 03:42:54AM -0000, Nuri Jung wrote:
> How about enabling subscription operator (`[]`) for generator expressions?
Generator expressions are iterators, and the iterator protocol is
intentionally very simple. You only need to provide two things for an
object to be an iterator:
* a method `__iter__` that returns self;
* a method `__next__` that returns the next generated value.
While there is nothing that prevents people from adding extra
functionality to their own custom iterator classes, the std lib
generally keeps iterators pretty simple.
We can talk about the practical difficulty of implementing such a thing
without providing either a very confusing user experience or being
exceeding memory inefficient, or both. Consider a generator
comprehension:
gen = (time.time() for i in itertools.cycle([None]))
How would you jump ahead to see what `gen[1000]` is? Having jumped
forward to `gen[1000]`, how do you jump back to give `gen[0]` without
storing the entire sequence?
The essence of subscription on sequences is that it gives random
access to a sequence of items. Trying to force random access on
arbitrary iterators that yield unpredictable values is hard.
Efficiency of on-demand calculation and convenience of random access do
not go well together. You can't have both except in very special
circumstances, e.g. range objects. (Which are not iterators!)
--
Steve
_______________________________________________
Python-ideas mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/UOL5O4ZXIDO3WCFKACAQCIIUJRD4WS7C/
Code of Conduct: http://python.org/psf/codeofconduct/