When running multiple coroutines concurrently using asyncio gather, the function creates task for each item. Now I want to get parent task which hash gather function in it! Is there a way to get parent task?
2 Answers
I do not see any "from a box" method to access "parent" task from "child", on the other hand you can just provide "child" task with reference to "parent" task and get all information regarding the parent task by the reference:
import asyncio
async def test_task(parent_task: asyncio.Task):
await asyncio.sleep(1)
print(f"Parent task name: {parent_task.get_name()}")
await asyncio.sleep(1)
async def amain():
print("Parent Task Start working")
await asyncio.gather(test_task(asyncio.current_task()))
print("Parent task Task Finished working")
if __name__ == '__main__':
loop = asyncio.get_event_loop()
_parent_task = loop.create_task(amain(), name="Parent Task")
loop.run_until_complete(_parent_task)
Comments
You can use asyncio.current_task for this:
test.py:
import asyncio
async def task(i, m):
print(f"START: {i} ({m.get_name()})")
await asyncio.sleep(i * 0.5)
print(f"END: {i}")
async def main():
m = asyncio.current_task()
tasks = []
for i in range(5):
tasks.append(asyncio.create_task(task(i, m)))
await asyncio.gather(*tasks)
if __name__ == "__main__":
asyncio.run(main())
Test:
$ python test.py
START: 0 (Task-1)
START: 1 (Task-1)
START: 2 (Task-1)
START: 3 (Task-1)
START: 4 (Task-1)
END: 0
END: 1
END: 2
END: 3
END: 4