I'm having a bit of trouble deciding how to break out of this coroutine if the except statement catches. Normally, I would just use:
def f(x):
try:
foo_var = next(a_volitile_generator(x))
except Exception:
print('it broked')
return
yield foo_var
However! I'm going to spawn a gazillion of these generator funcs, make them coroutines, and finally Futureize them & load them into an event-loop. Here's the issue:
loop = asyncio.get_event_loop()
queue = asyncio.Queue(maxsize=100)
async def f(x, result_queue, *, loop=loop):
while _some_condition() is True:
try:
foo_var = await a_volitile_async_generator(x)
except Exception:
print('it broked')
# HELP BELOW
raise StopAsyncIteration # <--ONLY OPTION????????
await result_queue.put(foo_var)
returning anything into the event-loop is a no-no in asyncio because you'll break everything...even if that value is None.
Aside from that, let's also say I'd like to avoid raising StopAsyncIteration...I'm trying to figure out if that's the only way to do this or if I have other options:
As mentioned by @dirn in the comments, you can replace your raise StopAsyncIteration line with a simple break:
async def f(x, result_queue, *, loop=loop):
while _some_condition() is True:
try:
foo_var = await a_volitile_async_generator(x)
except Exception:
print('it broked')
break
await result_queue.put(foo_var)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With