Message 306733 - Python tracker (original) (raw)
... result = list(await g(i) for i in range(3))
This is equivalent to this code:
async def ait(): for i in range(3): v = await g(i) yield v
result = list(ait())
Where 'ait' is an async generator function. You can't iterate it with the regular 'for x in ...' syntax, and you can't pass it to functions that expect a synchronous iterator (such as 'list').
Similarly, with synchronous code:
a = (i for i in range(3)) a[0] Traceback (most recent call last): File "", line 1, in TypeError: 'generator' object is not subscriptable
where '(' for ... ')' is another syntax for defining a synchronous generator.
... result = [await g(i) for i in range(3)]
This is equivalent to this code:
result = [] for i in range(3): v = await g(i) result.append(v)
I agree that PEP 530 is a bit vague about this and can be updated. I'll take a look into that.
Perhaps we can make the "TypeError: 'async_generator' object is not iterable" error message a bit clearer. Any ideas to improve it are welcome.
I would say that the first case should either behave as a second one, or raise a syntax error.
No, but we can improve error messages.