0Pricing
Python Academy · Lesson

Coroutines and the event loop

Define coroutines with async def and run them with asyncio.run().

Coroutines and the event loop is a free Python Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

What Is Concurrency?

Asyncio provides cooperative concurrency: a single thread handles many tasks by switching between them whenever one is waiting for I/O.

# Traditional: blocking I/O holds the whole thread
# Asyncio: while waiting for I/O, run other coroutines

import asyncio

async def main():
    print("Hello")
    await asyncio.sleep(1)   # yield control
    print("World")

asyncio.run(main())

async def — Coroutine Functions

Functions defined with async def are coroutine functions. Calling them returns a coroutine object; they only execute when awaited or scheduled.

import asyncio

async def greet(name):
    return f"Hello, {name}"

result = asyncio.run(greet("Alice"))
print(result)   # Hello, Alice

The Event Loop

The event loop drives coroutine execution. asyncio.run(coro) creates a new event loop, runs the coroutine to completion, and closes the loop.

import asyncio

async def compute():
    await asyncio.sleep(0)
    return 42

value = asyncio.run(compute())
print(value)   # 42

# For advanced use:
loop = asyncio.new_event_loop()
result = loop.run_until_complete(compute())
loop.close()

await Pauses Execution

await expr suspends the current coroutine until expr (another coroutine or future) completes. The event loop runs other tasks in the meantime.

import asyncio

async def task(name, delay):
    print(f"{name} starting")
    await asyncio.sleep(delay)
    print(f"{name} done")

async def main():
    await task("A", 2)
    await task("B", 1)   # sequential here

asyncio.run(main())

asyncio.sleep()

asyncio.sleep(seconds) suspends the current coroutine for the given time without blocking the event loop.

import asyncio

async def heartbeat():
    while True:
        print("ping")
        await asyncio.sleep(1)

# asyncio.run(heartbeat())  # runs forever

asyncio.run() Entry Point

asyncio.run(coro) is the standard top-level entry point. Never call it from inside a running event loop.

import asyncio

async def main():
    print("running")

if __name__ == "__main__":
    asyncio.run(main())

Checking if Inside an Event Loop

Use asyncio.get_running_loop() to detect if a loop is already running (raises RuntimeError if not).

import asyncio

async def inner():
    loop = asyncio.get_running_loop()
    print(f"Loop: {loop}")

asyncio.run(inner())

Running Blocking Code

Run CPU-bound or blocking-IO code without blocking the event loop using loop.run_in_executor(None, func, *args).

import asyncio, time

def blocking():
    time.sleep(2)
    return "done"

async def main():
    loop = asyncio.get_event_loop()
    result = await loop.run_in_executor(None, blocking)
    print(result)

asyncio.run(main())

Coroutine Chaining

Coroutines can await other coroutines, creating a chain. Control flows down the chain and returns up as each level completes.

import asyncio

async def fetch_data():
    await asyncio.sleep(1)
    return {"value": 42}

async def process():
    data = await fetch_data()
    return data["value"] * 2

async def main():
    result = await process()
    print(result)   # 84

asyncio.run(main())

Identifying Coroutines

Use asyncio.iscoroutine(obj) or asyncio.iscoroutinefunction(func) to inspect async functions at runtime.

import asyncio

async def my_coro():
    pass

print(asyncio.iscoroutinefunction(my_coro))   # True
coro = my_coro()
print(asyncio.iscoroutine(coro))              # True
coro.close()   # clean up the un-awaited coroutine

asyncio Debugging Mode

Enable debug mode to detect un-awaited coroutines, slow callbacks, and other issues: set PYTHONASYNCIODEBUG=1 or pass debug=True to asyncio.run.

import asyncio

async def main():
    pass

asyncio.run(main(), debug=True)

# Or:
# PYTHONASYNCIODEBUG=1 python script.py

Quick Check

What does asyncio.run(coro) do?

Recap

Define coroutines with async def, run them with asyncio.run(), and suspend them with await. The event loop cooperatively schedules coroutines, running others while one waits for I/O.

Frequently asked questions

Is the “Coroutines and the event loop” lesson free?

Yes — the full text of “Coroutines and the event loop” is free to read here on the web, and the Python Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO.

What will I learn in “Coroutines and the event loop”?

Define coroutines with async def and run them with asyncio.run(). You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Python Academy?

No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Coroutines and the event loop” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Python Academy lesson?

Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Coroutines and the event loop
  2. await, Tasks, and Gathering
  3. Async Context Managers and Iterators
  4. Async I/O Patterns in Production
← Back to Python Academy