Introduction to Python asyncio: Writing Fast, Concurrent Code

3D isometric illustration of a robot chef multitasking efficiently, representing Python's asyncio for concurrent programming.

Normal Python code is synchronous. It does one thing at a time. If you need to download 100 files, it downloads File 1, waits for it to finish, then starts File 2. This is slow because the CPU just sits there doing nothing while waiting for the network. To overcome such limitations, check out this Python asyncio guide to learn how to handle asynchronous operations efficiently.

Asynchronous code (using <a href="https://docs.python.org/3/library/asyncio.html">asyncio</a>) lets Python do other things while waiting. It can start all 100 downloads at once and just handle them as they finish.

The Keywords: async and await

To use asyncio, you need two new keywords:

  1. async def: Defines a special function (a “coroutine”) that can be paused.
  2. await: Tells Python “Pause here until this slow task is done, and go do something else in the meantime.”

A Simple Example

Let’s simulate a slow task, like fetching data from a server.

import asyncio
import time

# standard synchronous version
def fetch_sync(id):
    print(f"Starting fetch {id}...")
    time.sleep(2) # Simulate 2 second wait
    print(f"Finished fetch {id}")

# Async version
async def fetch_async(id):
    print(f"Starting fetch {id}...")
    await asyncio.sleep(2) # Non-blocking wait
    print(f"Finished fetch {id}")

# Main async function to run everything
async def main():
    # Start 3 tasks at the same time
    await asyncio.gather(
        fetch_async(1),
        fetch_async(2),
        fetch_async(3)
    )

# Running it
start = time.time()
asyncio.run(main())
end = time.time()
print(f"Total time: {end - start:.2f} seconds")

Result: The synchronous version would take 6 seconds (2+2+2). The async version takes only 2 seconds total, because they all ran at the same time!

Key Takeaways

  • Normal Python code is synchronous and processes tasks one at a time, which can be slow, especially for multiple downloads.
  • Asynchronous code using asyncio allows Python to handle multiple tasks simultaneously, improving efficiency.
  • Key keywords in asyncio are async def, which defines a coroutine, and await, which pauses execution while waiting for a task to finish.
  • An example shows that while the synchronous version takes 6 seconds, the async version only takes 2 seconds for 100 downloads.

Similar Posts

Leave a Reply