AsyncIO Deep Dive
Published by Brayan K
AsyncIO is the backbone of asynchronous programming in Python. To build high-performance systems — APIs, websocket servers, scrapers, automation pipelines, or distributed workers — you must fully understand how the event loop works, how Tasks provide concurrency, and how Futures act as low-level building blocks.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
async def makes a coroutine, and asyncio.run() runs it
This lesson shows the event loop, tasks and futures with small stand-in programs. The lead's APIs, websocket servers and scrapers have lessons of their own: Building APIs with FastAPI, Network Programming with sockets and Web Scraping with BeautifulSoup. Timeouts, cancellation, queues and limits on how many tasks run at once are in Advanced Async & Await Patterns.
A function written with async def is a coroutine function. Calling it runs none of its body, just as calling a generator function doesn't in Generators & Iterators Mastery: it hands back a coroutine object.
async def greet(name):
print("hello", name)
return "done"
coro = greet("Ada")
print(type(coro).__name__)
coro.close()
print("greet never ran")
# ✅ Expected output:
# coroutine
# greet never ranclose() throws the unused coroutine away quietly. A coroutine dropped without running makes Python print a warning, as an example below shows.
asyncio.run() starts an event loop, runs a coroutine on it to the end, and closes the loop. Inside a coroutine, await runs another coroutine and gives back what it returns:
import asyncio
async def greet(name):
print("hello", name)
return f"greeted {name}"
async def main():
result = await greet("Ada")
print(result)
print("before")
asyncio.run(main())
print("after")
# ✅ Expected output:
# before
# hello Ada
# greeted Ada
# afterForgetting await is the most common slip. The call makes a coroutine and drops it, so save() never runs:
import asyncio
async def save(item):
print("saving", item)
async def main():
save("report")
print("main finished")
asyncio.run(main())
# ✅ Expected output:
# main finishedPython also writes RuntimeWarning: coroutine 'save' was never awaited to the error output. This site's editor shows it under the output, marked ⚠️.
await works only inside async def:
import asyncio
def main():
await asyncio.sleep(0)
print("never printed")
# ✅ Expected error:
# SyntaxError: 'await' outside async functionAt the top of a file, outside any function, python3 stops with SyntaxError: 'await' outside function. This site's Run button runs your code inside an event loop of its own, so it accepts that, but python3 doesn't: start with asyncio.run(). Give asyncio.run() the coroutine, main(); given the function main, it stops with an error, a ValueError up to Python 3.13 and a TypeError from 3.14. And await needs a call too. await greet, without the brackets, stops with a TypeError, worded object function can't be used in 'await' expression up to Python 3.13 and 'function' object can't be awaited from 3.14. This example catches it, then makes the call:
import asyncio
async def greet():
return "hi"
async def main():
try:
print(await greet)
except TypeError:
print("await greet: TypeError")
print(await greet())
asyncio.run(main())
# ✅ Expected output:
# await greet: TypeError
# hiawait waits; to run things together, start them first
await asyncio.sleep(0) pauses the coroutine and lets the loop run something else, without waiting any time. The examples in this lesson use it where a real program would wait for a network reply or a file, so the order of the printed lines shows what runs when, with no clock involved:
import asyncio
async def cook(dish, steps):
for step in range(1, steps + 1):
print(f"{dish}: step {step}")
await asyncio.sleep(0)
return dish
async def main():
print("-- one after the other")
await cook("toast", 2)
await cook("eggs", 2)
print("-- together")
print(await asyncio.gather(cook("toast", 2), cook("eggs", 2)))
asyncio.run(main())
# ✅ Expected output:
# -- one after the other
# toast: step 1
# toast: step 2
# eggs: step 1
# eggs: step 2
# -- together
# toast: step 1
# eggs: step 1
# toast: step 2
# eggs: step 2
# ['toast', 'eggs']One after the other, each await waits for that cook() to finish. asyncio.gather() starts both, lets them take turns at each pause, and returns their results in the order you passed them.
asyncio.create_task() wraps a coroutine in a task, which the loop runs on its own. Awaiting the task later gives back its result:
import asyncio
async def cook(dish, steps):
for step in range(1, steps + 1):
print(f"{dish}: step {step}")
await asyncio.sleep(0)
return dish
async def main():
toast = asyncio.create_task(cook("toast", 2))
eggs = asyncio.create_task(cook("eggs", 2))
print("both started")
print(await toast, await eggs)
asyncio.run(main())
# ✅ Expected output:
# both started
# toast: step 1
# eggs: step 1
# toast: step 2
# eggs: step 2
# toast eggsA task starts at the next pause, and asyncio.run() cancels what's left
With the default task factory used here, create_task() schedules the coroutine, but doesn't run any of it yet. It starts the next time the coroutine that created it pauses:
import asyncio
async def worker():
print("worker starts")
async def main():
task = asyncio.create_task(worker())
print("task created")
print("done yet?", task.done())
await asyncio.sleep(0)
print("done now?", task.done())
asyncio.run(main())
# ✅ Expected output:
# task created
# done yet? False
# worker starts
# done now? TrueUntil it has finished, a task has no result to give, and asking for one is an error:
import asyncio
async def job():
await asyncio.sleep(0)
return 1
async def main():
task = asyncio.create_task(job())
print(task.result())
asyncio.run(main())
# ✅ Expected error:
# asyncio.exceptions.InvalidStateError: Result is not set.When main() returns, asyncio.run() lets the loop finish the round it's in, so tea prints its step 2, and then cancels every task still running. Step 3 never comes:
import asyncio
async def cook(dish, steps):
for step in range(1, steps + 1):
print(f"{dish}: step {step}")
await asyncio.sleep(0)
async def main():
asyncio.create_task(cook("tea", 3))
await asyncio.sleep(0)
print("main returns")
asyncio.run(main())
# ✅ Expected output:
# tea: step 1
# main returns
# tea: step 2Await the tasks you start, or they're cut off when main() ends.
The event loop takes turns at each pause, on one thread
A coroutine can be driven by hand. send(None) runs it up to its next pause, and when it finishes it raises StopIteration carrying its return value, as a generator does (Generators & Iterators Mastery's FAQ covers send()). This toy loop takes a coroutine from the front of a line, runs it to its next pause, and puts it back at the end:
import asyncio
async def count(name, n):
for i in range(1, n + 1):
print(name, i)
await asyncio.sleep(0)
return name + " done"
line = [count("A", 3), count("B", 2)]
while line:
coro = line.pop(0)
try:
coro.send(None)
line.append(coro)
except StopIteration as finished:
print(finished.value)
# ✅ Expected output:
# A 1
# B 1
# A 2
# B 2
# A 3
# B done
# A doneThe real loop, given the same coroutines, takes turns in the same order:
import asyncio
async def count(name, n):
for i in range(1, n + 1):
print(name, i)
await asyncio.sleep(0)
return name + " done"
async def main():
print(await asyncio.gather(count("A", 3), count("B", 2)))
asyncio.run(main())
# ✅ Expected output:
# A 1
# B 1
# A 2
# B 2
# A 3
# ['A done', 'B done']A coroutine only hands over its turn at an await that pauses. Work with no await in it keeps the turn until it's done, so the ticker waits:
import asyncio
async def busy():
print("busy starts")
total = sum(range(100_000))
print("busy ends", total)
async def ticker():
for i in range(3):
print("tick", i)
await asyncio.sleep(0)
async def main():
await asyncio.gather(busy(), ticker())
asyncio.run(main())
# ✅ Expected output:
# busy starts
# busy ends 4999950000
# tick 0
# tick 1
# tick 2That's why a long calculation, or a call that blocks such as time.sleep(), holds up every other task. Advanced Async & Await Patterns shows what to do instead.
Not every await pauses, either. Awaiting a coroutine that returns without waiting runs it inside the same turn; only a real wait, such as asyncio.sleep(), hands the turn on:
import asyncio
async def quick():
return 1
async def a():
for i in range(3):
await quick()
print("a", i)
async def b():
print("b runs")
async def main():
await asyncio.gather(a(), b())
asyncio.run(main())
# ✅ Expected output:
# a 0
# a 1
# a 2
# b runsgather() keeps your order, and one failure doesn't stop the others
Three downloads that need different numbers of pauses all start at once, and finish as each is ready. gather() still returns the results in the order you passed them:
import asyncio
async def download(name, steps):
print("start", name)
for _ in range(steps):
await asyncio.sleep(0)
print("finish", name)
return name.upper()
async def main():
files = await asyncio.gather(
download("a.txt", 3),
download("b.txt", 1),
download("c.txt", 2),
)
print(files)
asyncio.run(main())
# ✅ Expected output:
# start a.txt
# start b.txt
# start c.txt
# finish b.txt
# finish c.txt
# finish a.txt
# ['A.TXT', 'B.TXT', 'C.TXT']To handle each result as soon as it's ready, loop over asyncio.as_completed() instead:
import asyncio
async def download(name, steps):
for _ in range(steps):
await asyncio.sleep(0)
return name
async def main():
jobs = [download("a.txt", 3), download("b.txt", 1), download("c.txt", 2)]
for next_done in asyncio.as_completed(jobs):
print("finished:", await next_done)
asyncio.run(main())
# ✅ Expected output:
# finished: b.txt
# finished: c.txt
# finished: a.txtIf one of them fails, gather() raises that error straight away, but doesn't stop the others: slow carries on and finishes.
import asyncio
async def slow():
for _ in range(3):
await asyncio.sleep(0)
print("slow finished anyway")
return "slow"
async def bad():
raise ValueError("bad item")
async def main():
task = asyncio.create_task(slow())
try:
await asyncio.gather(task, bad())
except ValueError as e:
print("gather raised:", e)
print("slow cancelled?", task.cancelled())
print(await task)
asyncio.run(main())
# ✅ Expected output:
# gather raised: bad item
# slow cancelled? False
# slow finished anyway
# slowA TaskGroup cancels the rest instead (Python 3.11 and later), as Advanced Async & Await Patterns shows.
A Future is a box for a result, and a Task is a Future that runs a coroutine
A Future is an empty box for a result that something fills in later. Awaiting it waits until it's filled. Here the loop fills it: call_soon() runs a function at the loop's next turn.
import asyncio
async def main():
loop = asyncio.get_running_loop()
future = loop.create_future()
print("done?", future.done())
loop.call_soon(future.set_result, "parcel delivered")
print(await future)
print("done?", future.done())
asyncio.run(main())
# ✅ Expected output:
# done? False
# parcel delivered
# done? TrueA Task is a Future that fills itself with its coroutine's return value:
import asyncio
async def job():
await asyncio.sleep(0)
return 42
async def main():
task = asyncio.create_task(job())
print(isinstance(task, asyncio.Future))
print(task.done())
print(await task, task.done(), task.result())
asyncio.run(main())
# ✅ Expected output:
# True
# False
# 42 True 42A function added with add_done_callback() runs when the box is filled. The functions waiting on a Future run in the order they were added, and an await adds one of its own, for the code that waits. Here the callback is added before the await, so it prints first:
import asyncio
async def main():
loop = asyncio.get_running_loop()
future = loop.create_future()
future.add_done_callback(lambda f: print("callback got", f.result()))
loop.call_soon(future.set_result, 7)
print("awaited", await future)
await asyncio.sleep(0)
asyncio.run(main())
# ✅ Expected output:
# callback got 7
# awaited 7Add the callback after a task has started awaiting the Future, and the order flips: the task's awaited 7 comes before callback got 7.
Practice: two downloads at once
download() pauses once per step and returns the file name in capitals. Fill the three blanks: the keyword that makes download a coroutine function, the one that pauses at asyncio.sleep(0), and the asyncio function that runs both downloads and collects their results. The 👉 lines under the code give the answers, top to bottom.
import asyncio
___ def download(name, steps):
for _ in range(steps):
___ asyncio.sleep(0)
print(name, "done")
return name.upper()
async def main():
files = await asyncio.___(download("notes.txt", 2), download("photo.png", 1))
print(files)
asyncio.run(main())
# 👉 replace ___ with async
# 👉 replace ___ with await
# 👉 replace ___ with gather
# ✅ Expected output:
# photo.png done
# notes.txt done
# ['NOTES.TXT', 'PHOTO.PNG']photo.png finishes first because it pauses once and notes.txt twice, while the list keeps the order you passed. Without await before asyncio.sleep(0), nothing pauses: notes.txt finishes first, and Python warns that the coroutine sleep was never awaited. Without async, Python stops before running anything, with SyntaxError: 'await' outside async function.
On your own: a countdown for two
Write a coroutine function countdown(name, n) that prints the name and the number, from n down to 1, pausing once after each line, and returns the name followed by lift-off. Run countdown("Ana", 3) and countdown("Ben", 2) together, and print the list of their results.
import asyncio
# Write countdown() and main() here.
# your code hereimport asyncio
async def countdown(name, n):
while n > 0:
print(name, n)
n -= 1
await asyncio.sleep(0)
return f"{name} lift-off"
async def main():
results = await asyncio.gather(countdown("Ana", 3), countdown("Ben", 2))
print(results)
asyncio.run(main())
# ✅ Expected output:
# Ana 3
# Ben 2
# Ana 2
# Ben 1
# Ana 1
# ['Ana lift-off', 'Ben lift-off']
Practice quiz
async def hello(): return "hi". What does c = hello(), then print(type(c).__name__) print?
- coroutine
- function
- hi
- NoneType
Answer: coroutine. Calling an async def function runs none of its body. It hands back a coroutine object.
hello() is an async def function that prints hello. main() calls hello() without await, then prints end, and the program runs asyncio.run(main()). What is printed?
- hello, then end
- end, then hello
- It stops with SyntaxError: 'await' outside async function
- end, and a warning that hello was never awaited
Answer: end, and a warning that hello was never awaited. Without await, the call only makes a coroutine, which is thrown away unrun. Python warns about it on the error output.
main() does task = asyncio.create_task(hello()), where hello() prints hello, then print("created"), then await task, then print("awaited"). What is printed, in order?
- hello, created, awaited
- created, awaited
- created, hello, awaited
- hello, awaited
Answer: created, hello, awaited. create_task() only schedules hello(). It starts when main() pauses at await task.
cook(dish, steps) prints dish: step 1, dish: step 2 and so on, with await asyncio.sleep(0) after each line. main() does await cook("tea", 2), then await cook("jam", 2). What are the first three lines?
- tea: step 1, jam: step 1, tea: step 2
- jam: step 1, tea: step 1, tea: step 2
- tea: step 1, tea: step 1, jam: step 1
- tea: step 1, tea: step 2, jam: step 1
Answer: tea: step 1, tea: step 2, jam: step 1. Each await waits for that cook() to finish, and nothing else was started, so jam starts only after tea is done.
job(name, steps) pauses steps times with await asyncio.sleep(0), then returns name. What does print(await asyncio.gather(job("slow", 3), job("fast", 1))) show?
- ['fast', 'slow']
- ['slow', 'fast']
- ['slow']
- It stops with a ValueError
Answer: ['slow', 'fast']. gather() returns the results in the order you passed the coroutines, not the order they finished in.
job(name, steps) pauses steps times with await asyncio.sleep(0), then prints name and finished. What does await asyncio.gather(job("slow", 3), job("fast", 1)) print, in order?
- slow finished, fast finished
- fast finished
- fast finished, slow finished
- It stops with a ValueError
Answer: fast finished, slow finished. Both take turns at each pause. fast needs one pause and slow three, so fast finishes first.
ticker() prints tick 0 and tick 1, pausing with await asyncio.sleep(0) after each. crunch() prints start, adds up range(1000) with no await, then prints end. What does await asyncio.gather(ticker(), crunch()) print?
- tick 0, start, end, tick 1
- tick 0, tick 1, start, end
- start, end, tick 0, tick 1
- tick 0, start, tick 1, end
Answer: tick 0, start, end, tick 1. ticker() goes first and pauses after tick 0. crunch() has no await, so it keeps the turn until it's done.
slow() pauses three times, prints slow done and returns "slow"; bad() raises ValueError. main() makes task = asyncio.create_task(slow()), awaits asyncio.gather(bad(), task) inside try, prints caught in except ValueError, then print(task.cancelled()) and print(await task). What is printed?
- caught, True, then it stops with CancelledError
- caught, False, slow done, slow
- caught, then it stops with ValueError
- slow done, caught, False, slow
Answer: caught, False, slow done, slow. gather() raises the first error at once, but doesn't cancel the other task, which goes on and finishes.
Continue this course
- Previous: Generators & Iterators Mastery
- Next: Advanced Async & Await Patterns — Write clean asynchronous code with async/await and coroutines
- Quick reference: Python cheat sheet
Frequently asked questions
Does asyncio use more than one CPU core?
No. Everything in this lesson runs in one thread: threading.active_count() inside a coroutine gives 1. Tasks take turns, so asyncio helps a program that spends its time waiting, not one that spends it calculating. Concurrency in Python: Threads vs Processes compares the options.
How do I run a coroutine from an ordinary function?
With asyncio.run(), as long as no event loop is already running there: def total(): return asyncio.run(add(2, 3)) gives 5 under python3. This site's Run button runs every program inside an event loop of its own, so there asyncio.run() works only at the top level of your code, not inside a function.
Does asyncio.run() return a value?
Yes: whatever the coroutine returns. With main() returning {"status": "ok"}, result = asyncio.run(main()) makes result["status"] give ok.
How can I tell a coroutine function from an ordinary one?
inspect.iscoroutinefunction() says so: True for a function written with async def, False for one written with def.
What happened to @asyncio.coroutine?
Before async def existed, coroutines were generators marked with @asyncio.coroutine. It was removed in Python 3.11: hasattr(asyncio, "coroutine") gives True on 3.10 and False from 3.11 on. Write async def instead.
Can a program wait for several web requests at once?
Yes: start them all, as gather() and as_completed() do with stand-ins in this lesson, and handle each answer as it arrives. The requests library from HTTP Requests & APIs can't be awaited, so async programs use an async HTTP library such as aiohttp or httpx, installed with pip. This site's editor has neither installed.