[Python-Dev] Tricky way of of creating a generator via a comprehension expression

Yury Selivanov yselivanov.ml at gmail.com
Wed Nov 22 15:07:45 EST 2017


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.

I also don't recall seeing a lot of `list(x for x in ...)` pattern.
Usually people just use list or dict comprehensions directly (and they
are faster, btw).

Yury


More information about the Python-Dev mailing list