Reputation: 69
After the task already completed, is there any difference between await asyncio.Task
and asyncio.Task.result()
?
The only difference in the following code is how I read the value in task
.
import asyncio
from asyncio import TaskGroup
async def func():
await asyncio.sleep(2)
return 0
async def main():
async with TaskGroup() as tg:
task = tg.create_task(func())
print(await task)
asyncio.run(main())
vs
import asyncio
from asyncio import TaskGroup
async def func():
await asyncio.sleep(2)
return 0
async def main():
async with TaskGroup() as tg:
task = tg.create_task(func())
# The await is implicit when the context manager exits.
print(task.result())
asyncio.run(main())
Which code is the preferred one?
Upvotes: 0
Views: 40
Reputation: 17342
The source code snippet below shows that await task
ends up calling task.result()
if the task is done. So the answer is: no difference in this case.
def __await__(self):
if not self.done():
self._asyncio_future_blocking = True
yield self # This tells Task to wait for completion.
if not self.done():
raise RuntimeError("await wasn't used with future")
return self.result() # May raise too.
# location: asyncio/futures.py, in class _Future,
# the Task class is derived from it
Upvotes: 1