Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Use `any` with an `async_generator` Inside a Generator Expression

If I have a regular iterable object in Python I can use any and a generator comprehension to get boolean. E.g.

from pathlib import Path

path = Pathlib("/foo/bar/baz")
has_contents = any(path.iterdir())

And I can do the same thing with an async_generator and list comprehension:

is_empty = any([x async for x in async_generator])

But it doesn’t seem to be possible to do the same with an async_generatorand a generator comprehension.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

not_empty = any(x async for x in foo.iter())

raises

TypeError: 'async_generator' object is not iterable

Is there a way to use an async_generator inside a generator comprehension?

>Solution :

The problem is not using an async_generator in a generator comprehension. That part is fine.

>>> async def ag():
...     yield 0
...     yield 1
... 
>>> (x async for x in ag())
<async_generator object <genexpr> at 0x7fffe34fd640>

The issue is consuming an async generator with a function that expects a synchronous iterator.

In this case, you can’t iterate it with the regular for x in ... syntax, and you shouldn’t pass it to functions that expect a synchronous iterator, such as any. You’ll see the same problem with list(...).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading