Urgent.News

What's breaking now, across hundreds of outlets.

Tech

Asyncio Explained Simply: A Beginner's Guide to Python Async

4 min read · 756 words Imagine you are cooking breakfast. You put bread in the toaster, crack two eggs into a frying pan, and brew coffee. If you cooked synchronously , you would stand motionless in front of the toaster for two minutes. Only after the toast popped up would you turn to crack the eggs. You'd wait for the eggs to finish before grinding coffee beans. That is a terrible way to make…

Imagine a typical breakfast routine. You'd place bread in a toaster, crack eggs into a frying pan, and brew coffee. If you followed this sequence synchronously, you'd stand still for two minutes, waiting for the toast to pop up before cracking eggs, and then grinding coffee beans. This approach is inefficient and inefficiently handles I/O-bound code.

Python's asyncio library avoids these inefficiencies. It enables a single thread to pause an operation while waiting for an external system such as a database, API, or file read, and execute other tasks meanwhile. Understanding asyncio requires three core concepts: the event loop, coroutines, and await keywords. The event loop acts as the central engine, tracking tasks and delegating execution. When a task waits for a network response, the event loop suspends it and resumes another task.

Coroutines, declared with async def, are functions that are not executed immediately upon call. Instead, they return coroutine objects ready to be scheduled on the event loop. The await keyword yields execution back to the event loop, signaling Python to go do other work until the awaited operation produces a result.

To illustrate, let's compare sequential code to concurrent asynchronous execution using asyncio.sleep, which simulates network latency. Importing asyncio and time modules, we define an asynchronous function fetch_data that fetches data from different sources with varying delays. Using asyncio.gather, we submit three fetch_data tasks to the event loop and wait until all complete.

Sequentially, this script would take 4.5 seconds (2.0 + 1.0 + 1.5). However, with asyncio, it finishes in roughly 2.0 seconds, equal to the longest task's duration.

Real-world applications of asyncio shine when interacting with third-party web services. Consider making multiple LLM requests concurrently using the Anthropic Python SDK. We initialize an asynchronous client, define a generate_summary function to create summaries for various topics, and run all requests concurrently using asyncio.gather. In comparison to sequential execution, asyncio allows all requests to fire nearly simultaneously, significantly reducing total execution time.

While using asyncio, be cautious of common traps. Don't call blocking code inside coroutines, as this freezes the entire event loop. Always use asynchronous equivalents of blocking functions like time.sleep or requests.get to ensure efficient concurrent execution.

Rewritten by urgent.news; may contain errors — check the original.

Source: dev.to

Read the original at dev.to →

Report a problem with this story

More in Tech

I built a case compatibility checker covering 67 phone models (and open-sourced it)

Why I built this I run a phone accessories blog. Every week the same question shows up in comments and support emails: "I have a Galaxy S24 Ultra — which case fits it?" I was answering it by hand…

  • Author created Case Compatibility Checker for 67 phone models
  • Tool includes cases, screen protectors, buying guides
  • Project open-sourced under MIT license on GitHub

9,045 internet-reachable Couchbase instances: measuring the document database layer

9,045 internet-reachable Couchbase instances: measuring the document database layer Opening Couchbase is a distributed document database.

  • 9,045 Couchbase instances reachable via public internet identified in September 2026
  • Couchbase operates as a distributed database system with multiple services
  • Web console and data/query services serve different client access purposes

More from Monday 12 October →