Is asyncio part of Python?

Mar 17, 2024 ยท 2 min read

Python's asyncio module provides infrastructure for writing concurrent code using the async/await syntax. So while asyncio is not a part of the Python standard library, it is included with Python 3.7 and higher.

Why Async IO?

The async/await keywords in Python enable a paradigm called asynchronous programming. This allows you to write non-blocking code that can efficiently utilize I/O resources without causing the program to wait.

Some key benefits of asyncio:

  • Improved performance - By not blocking on I/O, CPU time can be used for other tasks. This allows for faster throughput overall.
  • Increased scalability - Async code can handle many concurrent connections with fewer system resources.
  • Better user experience - UI remains responsive while awaiting long running tasks.
  • Let's look at a quick example:

    import asyncio
    
    async def fetch_data():
        print('start fetching')
        await asyncio.sleep(2) # simulate a 2 second delay
        print('done fetching')
        return {'data': 1}
    
    async def print_numbers():
        for i in range(10):
            print(i)
            await asyncio.sleep(0.25)
    
    async def main():
        task1 = asyncio.create_task(fetch_data())
        task2 = asyncio.create_task(print_numbers())
    
        value = await task1
        print(value)
        await task2
    
    asyncio.run(main())

    This concurrently runs two async functions without blocking the main thread.

    How to Use Asyncio

    The asyncio module includes classes like Task and EventLoop to manage the control flow. The asyncio.run() method sets up the event loop and executor to run until complete.

    The key takeaways are:

  • Asyncio comes built-in with Python 3.7 and above
  • It enables non-blocking concurrency via the async/await syntax
  • This allows efficient utilization of system resources
  • And overall better throughput, scalability and UX
  • So while asyncio is not part of the Python standard library, it is included with Python by default. This makes async programming a built-in capability of the language.

    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: