On Sat, May 9, 2020 at 11:15 AM Ram Rachum ram@rachum.com wrote:
Here's an idea I've had. How about instead of this:
itertools.islice(iterable, 7, 20)
We'll just have:
itertools.islice(iterable)[7:20]
Advantages:
- More familiar slicing syntax.
- No need to awkwardly use None when you're interested in just specifying
the end of the slice without specifying the start, i.e. islic(x)[:10] instead of islice(x, None, 10) 3. Doesn't require breaking backwards compatibility.
What do you think?
Looking at this, my train of thought was:
While we're at it, why not allow slicing generators? And if we do that, what about regular indexing? But then, what if I do `gen[3]` followed by `gen[1]`? Is it an error? Does the generator have to store its past values? Or is `gen[1]` the second item after `gen[3]`? Or wherever the generator last stopped? Well that's probably why I can't index or slice generators - so that code doesn't accidentally make a mess trying to treat a transient iterator the way it does a concrete sequence. A generator says "you can only iterate over me, don't try anything else".
Which leads us back to your proposal. `islice(iterable)[7:20]` looks nice, but it also allows `foo(islice(iterable))` where `foo` can do its own indexing and that's leading to dangerous territory.