Issue
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_generator
and a generator comprehension.
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(...)
.
Answered By - wim
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.