If I have a function that's emitting results from an async for loop, what is the best way to "short circuit" the loop so the caller can close their async for loop without blocking forever?
For example,
async def _get_items_in_range(a, b): ... ... while items := await cursor.to_list(length=100): found = True for obj in items: yield self._up_last(obj) if not found: ??? async def window(a, b) -> AsyncIterable[Any]: async for item in self._get_items_in_range(a, b): # <-- this can block forever yield item I tried using the async-timeout library, and I can skip the async for loop after a short delay, however, I don't know how to bubble "no items" further down the stack. I thought raising StopAsyncIteration would work, but it does not. The lower async for loop is expecting something I just don't know what it is, or what I can give it to close nicely.
This is different than my similar question What is the correct way to combine async-for with an if condition to break mid await? , because that was supposed to block until the next item (or shutdown had been called), whereas this solution needs to break semi-immediately if there's nothing there and not break the (or add additional) code to the caller.
https://stackoverflow.com/questions/66729029/how-can-i-short-circuit-async-for-loop-with-no-items March 21, 2021 at 01:05PM
没有评论:
发表评论