1

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.

1 Answer 1

1

The task is removed from all_tasks() when it is destroyed.

Add a del statement:

 [...] await t del t print(len(asyncio.Task.all_tasks())) 

and it will yield:

1 2 request 1 
Sign up to request clarification or add additional context in comments.

2 Comments

therefore,asyncio.Task.all_tasks will return finished tasks until I will clear all variables, that referencing on it in my program
Fixed in github.com/python/cpython/pull/7174. asyncio.all_tasks() now only returns pending tasks.