On Nov 18, 2019, at 04:32, Ned Batchelder <n...@nedbatchelder.com> wrote:
> 
> There are uses for comprehension syntax for making tuples, but they occur far 
> far less frequently than the comprehensions we have.  To me, the existing way 
> to do it makes perfect sense, and exactly expresses what needs to happen:
> 
>     tuple(i for i in range(10))
> 

It’s worth noting that this isn’t 100% identical to what a tuple comprehension 
would do—but only to know exactly what the differences are so we can conclude 
they don’t matter.

    def stop(): raise StopIteration
    a = list(stop() if i%3==2 else I for i in range(10))
    b = [stop() if i%3==2 else I for i in range(10)]

The second line will construct a = [0,1], but the third will raise a 
StopIteration to the user and not construct anything or bind b. You can also 
put the stop() in an if clause.

Back around 3.2-ish, the way comprehensions were defined implied that these 
should be identical. I looked into whether we could add this behavior to 
listcomps (or actually implement a listcomp on top of a genexpr without a 
performance cost). But the overwhelming consensus was that this is an 
antipattern and the right fix was to change the docs. (Also, there used to be 
more varied opportunities for this kind of hackery, but now they raise 
RuntimeError.)

So, a tuple comprehension would disallow this antipattern, it would avoid the 
problem that tuple is a plain old name that can be shadowed or rebound, it 
would be slightly faster (in 3.2 or wherever, IIRC, it was around a 30% 
difference in overhead, but the overhead isn’t significant except in trivial 
comprehensions), and the stack would look different from functions called from 
inside the comprehension.

There’s also the readability difference, but I can’t see how a comma in an odd 
place is more readable than the name tuple is, unless people need to embed 
these in the middle of more complex expressions so brevity helps (as people 
definitely do need to do for, e.g., simple tuple literals).

Is any of that a good enough reason for new display syntax? I don’t think so.

_______________________________________________
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/3MRAHALF6DUD6WEBWQUZA4RADCYZIPVT/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to