On 09/06/2022 10:28, Paul Moore wrote:
On 09/06/2022 09:50, Paul Moore wrote:
On Thu, 9 Jun 2022 at 01:12, Steve Jorgensen <ste...@stevej.name> wrote:
My current thinking in response to that is that using islice is a decent
solution except that it's not obvious. You have to jump outside of the thinking
about the destructuring capability and consider what else could be used to
help. Probably, first thing that _would_ come to mind from outside would be
slicing with square brackets, but that would restrict the solution to only
work with sequences and not other iterables and iterators as islice does.
That brings up a tangential idea. Why not allow square-bracket indexing of
generators instead of having to import and utilize islice for that?
Because generators don't have a common (sub-)type, so there's no class
to put the relevant __getitem__ method on.
How so?
>>> def mygen(): yield 42
...
>>> type(mygen())
<class 'generator'>
Sorry, I was assuming the request was for slicing to work for
iterables, not generators. But do we really want to make slicing work
for generators, but still fail for other iterators? That seems like
it'll just cause confusion. Take the OP's original example:
with open("some.file") as f:
for line in f[:10]:
# This fails because f isn't a generator
with open("some.file") as f:
for line in (l for l in f)[:10]:
# This does work because we're slicing a generator
You're bound to get someone (possibly even the OP!!!) asking for the
first version to "just work"...
Also, "obvious" cases like
# How we would do this currently
def get_first_3_current(i):
return list(itertools.islice(i, 3))
# How someone might assume we could do this with the new indexing
def get_first_3(i):
return list(i[:3])
get_first_3(range(10))
get_first_3({1,2,3,4})
get_first_3({"a": "one", "b": "two", "c": "three"})
won't work, and no amount of adding iter() will make them work.
Paul
Well, you can write
for line in f.readlines()[:10]:
But taking the general point:
Yes, it would no doubt cause confusion if some iterators supported
slicing and other's didn't. But it would be a useful feature.
Slicing could be added piecemeal to iterators such as open() according
to demand.
Of course, for non-reusable iterators it would be forbidden to go
backwards (or even remain in the same place):
agen[42]
agen[41]
ValueError: Generator has been used up past the slice point. (Better
wordings are doubtless available.)
I realise this is asking for a lot of work do be done.🙁
Rob Cliffe
_______________________________________________
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/U2BXTPTME5WBQPPIHEJH5HE5XNGVRSDP/
Code of Conduct: http://python.org/psf/codeofconduct/