Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to break out of a asyncio coroutine without using the `return` statement?

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:

like image 214
Rob Truxal Avatar asked Sep 14 '25 01:09

Rob Truxal


1 Answers

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)
like image 53
Zero Piraeus Avatar answered Sep 16 '25 16:09

Zero Piraeus