Async Python Class
If needing to run async code when initializing a Class, the following worked for me;
class A():
async def async_init(self):
await self.calc()
return self
def __await__(self):
return self.async_init().__await__()
async def calc(self):
return 1 + 1
A full example:
#!/usr/bin/python
import asyncio
class A():
def __init__(self):
self.sum = await self.calc()
async def async_init(self):
self.sum = await self.calc()
return self
def __await__(self):
return self.async_init().__await__()
async def calc(self):
return 1 + 1
async def main():
a = await A().calc()
print(a)
if __name__ == "__main__":
asyncio.run(main())