[Python-Dev] Tricky way of of creating a generator via a comprehension expression (original) (raw)

Ivan Levkivskyi levkivskyi at gmail.com
Wed Nov 22 18:46:49 EST 2017


On 22 November 2017 at 21:07, Yury Selivanov <yselivanov.ml at gmail.com> wrote:

On Wed, Nov 22, 2017 at 2:37 PM, Ivan Levkivskyi <levkivskyi at gmail.com> wrote: > On 22 November 2017 at 20:33, Guido van Rossum <guido at python.org> wrote: >> >> On Wed, Nov 22, 2017 at 11:12 AM, Ivan Levkivskyi <levkivskyi at gmail.com_ _> >> wrote: >>> >>> On 22 November 2017 at 20:05, Guido van Rossum <guido at python.org> wrote: >>>> >>>> On Wed, Nov 22, 2017 at 10:54 AM, Jelle Zijlstra >>>> <jelle.zijlstra at gmail.com> wrote >>>>> >>>>> 2017-11-22 9:58 GMT-08:00 Guido van Rossum <guido at python.org>: >>>>> >>>>> (OTOH, await in the same position must keep working since it's not >>>>> broken and not unintuitive either.) >>>> >>>> >>> >>> >>> This is very questionable IMO. >>> So do you think that [await x for y in z] and list(await x for y in z)

Comprehensions are declarative, and that's why [], and {} work with async/await. When you're using parens () you explicitly tell Python compiler that you want a generator expression. And the distinction between comprehensions and generator expressions also exists for synchronous code: x = [a for a in range(10)] x[0] and x = (a for a in range(10)) x[0] # TypeError Is the above "intuitive" for all Python users? Probably not. Write it once, get your TypeError, read the error message and you understand what's going on here. Is the difference between "[await x for y in z ]" and "list(await x for y in z)" intuitive for all Python users? Again, probably not. But for those who write async code it is.

Just found another example of intuitive behaviour:

async def f(): ... for i in range(3): ... yield i ... async def g(): ... return [(yield i) async for i in f()] ... g().send(None) Traceback (most recent call last): File "", line 1, in File "", line 2, in g TypeError: object async_generator can't be used in 'await' expression

of course it is obvious for anyone who writes async code, but anyway an interesting example.

-- Ivan -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-dev/attachments/20171123/cf79e193/attachment.html>



More information about the Python-Dev mailing list