
Tasks in the Background
asyncio.create_task(coro) wraps a coroutine in a Task and schedules
it to run soon, in the background. You get the Task back right away.
async def main():
task = asyncio.create_task(fetch_map("Ember"))
print("task created") # runs first!
result = await task # wait for its result
Note the timing: a new task doesn't start the moment you create it.
It starts the next time the current coroutine yields (hits an
await that has to wait). That's why "task created" prints first.
Tasks are great when you want to kick off work, do something else, and collect the result later. Awaiting a task that already finished just hands you the result instantly.
Always keep a reference to your tasks, in a variable or a list. The event loop only holds a weak reference, so a forgotten task can be thrown away before it finishes.
Assignment
Fill in the four blanks ___:
- Turn both
brew(...)calls into background tasks. - Await each task to collect its result.
The program should print the results and then the event log.
Fill in the four blanks ___:
- Turn both
brew(...)calls into background tasks. - Await each task to collect its result.
The program should print the results and then the event log.
Press Run to try your code, then Check to test it.