I want to run coroutines in __init__, I am using asyncio.create_task to start the execution of the coroutine inside a non-async func (i.e. __init__) to set instance attributes. I need to wait for the first task to finish before returning from __init__. I cannot await the task in __init__, so I tried to use the result of task.done() to check whether it's finished but it did not work, the code got hung and never returned from __init__.
Here's a simple example:
async def coro():
await asyncio.sleep(2)
return 2
class Foo:
def __init__(self):
self._job_id_task = asyncio.create_task(coro()) #Starts running coro()
while not self._job_1_task.done():
pass
self.job_id = self._job_id_task.result()
foo = Foo() #gets hung and never returns Foo object.
Based on my sample code above, I was expecting foo = Foo() to create Foo object in little over 2 seconds, but execution on line foo = Foo() gets hung and never finishes.