First example:
import asyncio async def req(): print('request') await asyncio.sleep(1) async def run(): print(len(asyncio.Task.all_tasks())) asyncio.ensure_future(req()) print(len(asyncio.Task.all_tasks())) await asyncio.sleep(2) print(len(asyncio.Task.all_tasks())) loop = asyncio.get_event_loop() loop.run_until_complete(run()) The result is:
1 2 request 1 Second example:
import asyncio async def req(): print('request') await asyncio.sleep(1) async def run(): print(len(asyncio.Task.all_tasks())) t = asyncio.ensure_future(req()) print(len(asyncio.Task.all_tasks())) await t print(len(asyncio.Task.all_tasks())) loop = asyncio.get_event_loop() loop.run_until_complete(run()) The result is:
1 2 request 2 So, why in first example the last call asyncio.Task.all_tasks() return 1 and in second example it's return 2? In other words, why in first example the task, that wrap req() was deleted from a set of all tasks for an event loop, and why it is not true for the second example.