Master Python asyncio: From Coroutines to Event Loops Explained

This article introduces Python's asyncio library, explains how coroutines are defined and run, demonstrates event‑loop management with run_until_complete and run_forever, covers callbacks, gathering multiple coroutines, and best practices for closing loops, all illustrated with clear code screenshots.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Python asyncio: From Coroutines to Event Loops Explained

What is asyncio?

Python's asyncio library is comparable to C++ Boost.Asio and provides asynchronous I/O, allowing you to start an I/O operation without waiting for it to finish and receive a notification when it completes.

Concurrency in Python

Asyncio is one way to achieve concurrency; Python can also use threading and multiprocessing. Because of the Global Interpreter Lock (GIL), neither asyncio nor multithreading offers true parallelism.

Coroutines

A task that can be handed to asyncio is called a coroutine . A coroutine can yield execution to others using await (or the older yield from).

Coroutines are defined with the async def syntax.

For example, do_some_work is a coroutine function, which can be verified with asyncio.iscoroutinefunction.

To simulate work, the coroutine can sleep for a few seconds.

Running Coroutines

Calling a coroutine function returns a coroutine object; it does not start execution until the event loop runs it. You can check the object with asyncio.iscoroutine.

Two ways to run a coroutine object are shown: using the default loop's run_until_complete or manually starting the loop.

run_until_complete

blocks until the coroutine finishes, internally wrapping the coroutine into a Future via ensure_future.

Callbacks

When a coroutine represents an I/O read, you can attach a callback to its future to be notified when the read completes.

Multiple Coroutines

In real projects you often run several coroutines concurrently in one loop. Use asyncio.gather to schedule them together.

Alternatively, store coroutine objects in a list and pass the list to gather.

The combined future completes when the longest‑running coroutine finishes, not when the sum of durations is reached.

run_until_complete vs. run_forever

run_until_complete

blocks until the given future finishes. run_forever runs the loop indefinitely until loop.stop() is called, which must be done from within a coroutine.

Stopping the loop prematurely can abort other coroutines; a common solution is to wrap all coroutines with gather, add a callback, and stop the loop from that callback.

Closing the Loop

The event loop can be reused as long as it is not closed. Closing it releases resources and prevents accidental reuse.

gather vs. wait

asyncio.gather

and asyncio.wait provide similar functionality; refer to StackOverflow for detailed differences.

Timer

C++ Boost.Asio offers a timer object for I/O; Python lacks a native timer but you can simulate one with asyncio.sleep.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

concurrencyasynchronous programmingcoroutineevent loopasyncio
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.