[issue32113] Strange behavior with await in a generator expression

Yury Selivanov report at bugs.python.org
Wed Nov 22 10:46:59 EST 2017


Yury Selivanov <yselivanov at gmail.com> added the comment:

> ...     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 "<stdin>", line 1, in <module>
  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.

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue32113>
_______________________________________


More information about the Python-bugs-list mailing list