Executing Asyncio Coroutines: How Often to Call run()

Mar 24, 2024 ยท 2 min read

The asyncio.run() function is used to execute asyncio coroutine functions. A common question that comes up is how many times and where run() should be called in an asyncio program.

run() should generally only be called once per asyncio program. It sets up the asyncio event loop, runs the passed-in coroutine, and then closes the loop when the coroutine completes. Calling it more than once per program can lead to unexpected behavior.

Here is an example usage:

import asyncio

async def main():
    print('hello')
    await some_coroutine()

asyncio.run(main())

The main() coroutine is passed into run(), which takes care of executing it and cleaning up the event loop afterwards.

There are a few cases where calling run() multiple times may make sense:

  • In REPL environments like Jupyter notebooks, you may want to call run() multiple times to execute different coroutines.
  • In long-running services, you may want to set up a loop once with get_event_loop() and then call run_until_complete() multiple times for different coroutines.
  • In tests, it can be useful to create multiple loops to isolate behavior.
  • In general though, for most scripts and programs, run() should be called just once. The key is to structure your code to have a single entry point coroutine that handles any coordination or orchestration needed between other coroutines.

    Properly understanding how to initialize and clean up asyncio event loops takes some experience. Follow these best practices around run(), and you'll be on your way to writing efficient asyncio programs.

    Browse by tags:

    Browse by language:

    The easiest way to do Web Scraping

    Get HTML from any page with a simple API call. We handle proxy rotation, browser identities, automatic retries, CAPTCHAs, JavaScript rendering, etc automatically for you


    Try ProxiesAPI for free

    curl "http://api.proxiesapi.com/?key=API_KEY&url=https://example.com"

    <!doctype html>
    <html>
    <head>
        <title>Example Domain</title>
        <meta charset="utf-8" />
        <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
    ...

    X

    Don't leave just yet!

    Enter your email below to claim your free API key: