[Python-ideas] PEP 530: Asynchronous Comprehensions

Chris Angelico rosuav at gmail.com
Mon Sep 5 21:17:22 EDT 2016


On Tue, Sep 6, 2016 at 9:27 AM, Sven R. Kunze <srkunze at mail.de> wrote:
> Hi Yury,
>
> just for my understanding:
>
> On 04.09.2016 01:31, Yury Selivanov wrote:
>>
>> We propose to allow the use of ``await`` expressions in both
>> asynchronous and synchronous comprehensions::
>>
>>     result = [await fun() for fun in funcs]
>>     result = {await fun() for fun in funcs}
>>     result = {fun: await fun() for fun in funcs}
>>
>
> This will produce normal lists, sets and dicts, right?
>
> Whereas the following will produce some sort of async lists, sets, and
> dicts?
>
>>     result = [await fun() async for fun in funcs]
>>     result = {await fun() async for fun in funcs}
>>     result = {fun: await fun() async for fun in funcs}
>
>
> If so, how do I read values from an async list/set/dict?

AIUI they won't return "async lists" etc; what they'll do is
asynchronously return list/set/dict. Imagine an async database query
that returns Customer objects. You could get their names thus:

names = [cust.name async for cust in find_customers()]

And you could enumerate their invoices (another database query) with a
double-async comprehension:

invoices = {cust.name: await cust.list_invoices() async for cust in
find_customers()}

As always, you can unroll a comprehension to the equivalent statement form.

_tmp = {}
async for cust in find_customers():
    _tmp[cust.name] = await cust.list_invoices()
invoices = _tmp

or with the original example:

_tmp = []
async for fun in funcs:
    _tmp.append(await fun())
result = _tmp

Hope that helps.

ChrisA


More information about the Python-ideas mailing list