Get task result from an asyncio Task object?

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
larsks
Posts: 22
Joined: Mon Feb 13, 2017 5:27 pm

Get task result from an asyncio Task object?

Post by larsks » Sat Feb 05, 2022 2:53 am

In regular Python, I can retrieve the result of a task using the .result() method:

Code: Select all

t = asyncio.create_task(sometask())
await t
print('result:', t.result())
uasyncio.Task objects don't have a .result() method, but they do have a .data attribute, and when .done is true, .data.value appears to have the task result. This isn't documented anywhere; can I rely on it? It's useful when trying to implement something like asyncio.wait() or asyncio.as_completed(), where one wants to return the task object but calling code may want the task result.

fivdi
Posts: 16
Joined: Thu Feb 03, 2022 10:28 pm
Contact:

Re: Get task result from an asyncio Task object?

Post by fivdi » Sat Feb 05, 2022 11:53 am

This should work:

Code: Select all

t = asyncio.create_task(sometask())
result = await t
print('result:', result)

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: Get task result from an asyncio Task object?

Post by pythoncoder » Mon Feb 07, 2022 12:21 pm

That is also portable to CPython.
Peter Hinch
Index to my micropython libraries.

Post Reply