Search code examples
pythonasync-awaitpython-asynciocontextmanager

Is there a Pythonic way to run async task in background similar to using a contextmanager?


Recently I wanted to run some asynchronous tasks in the background while running other tasks but I didn't think the code was Pythonic enough:

task = asyncio.create_task(long_task())
await short_task()
await task

So I made it more Pythonic:

@asynccontextmanager
async def run_in_background(coro):
    task = asyncio.create_task(coro)
    yield task
    await task


async def main():
    async with run_in_background(long_task()):
        await short_task()

Does something like this already exist? If not is this considered more Pythonic or less Pythonic than the existing way?


Solution

  • trio provides a better way to do this with nursery objects:

    async with trio.open_nursery() as nursery:
        nursery.start_soon(long_task)  # Task will run in background
    
        await short_task()
        # Wait for background tasks to finish