On Tue, Nov 29, 2016 at 8:22 PM, Chris Angelico <ros...@gmail.com> wrote: > Interestingly, I can't do that in a list comp: > >>>> [x async for x in aiterable] > File "<stdin>", line 1 > [x async for x in aiterable] > ^ > SyntaxError: invalid syntax > > Not sure why.
Because you tried to use an async comprehension outside of a coroutine. py> [x async for x in y] File "<stdin>", line 1 [x async for x in y] ^ SyntaxError: invalid syntax py> async def foo(): ... [x async for x in y] ... The same is true for async generator expressions. The documentation is clear that this is illegal for the async for statement: https://docs.python.org/3.6/reference/compound_stmts.html#the-async-for-statement I don't see anything about async comprehensions or async generators outside of the "what's new" section, but it stands to reason that the same would apply. On Tue, Nov 29, 2016 at 11:06 PM, Frank Millman <fr...@chagford.com> wrote: >>>> async def main(): > > ... print(list(x async for x in gen(5))) > > ... >>>> >>>> loop.run_until_complete(main()) > > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > File > "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\asyncio\base_events.py", > line 466, in run_until_complete > return future.result() > TypeError: 'async_generator' object is not iterable Yeah, that's what I would expect. (x async for x in foo) is essentially a no-op, just like its synchronous equivalent; it takes an asynchronous iterator and produces an equivalent asynchronous iterator. Meanwhile, list() can't consume an async iterator because the list constructor isn't a coroutine. I don't think it's generally possible to "synchronify" an async iterator other than to materialize it. E.g.: def alist(aiterable): result = [] async for value in aiterable: result.append(value) return result And I find it a little disturbing that I actually can't see a better way to build a list from an async iterator than that. -- https://mail.python.org/mailman/listinfo/python-list