<p>You can inherit your class from <code>AsyncMixin</code> and implement <code>ainit</code> method, there you can use async functions:</p>
<pre><code>import asyncio
class AsyncMixin:
def init(self, *args, **kwargs):
"""
Standard constructor used for arguments pass
Do not override. Use ainit instead
"""
self.__storedargs = args, kwargs
self.async_initialized = False
async def __ainit__(self, *args, **kwargs):
"""Async constructor, you should implement this"""
async def __initobj(self):
"""Crutch used for __await__ after spawning"""
assert not self.async_initialized
self.async_initialized = True
# pass the parameters to __ainit__ that passed to __init__
await self.__ainit__(*self.__storedargs[0], **self.__storedargs[1])
return self
def __await__(self):
return self.__initobj().__await__()
class CosmosClient():
pass
class CosmosCRUD(AsyncMixin):
def init(self, client: CosmosClient):
self.client = client
super().init()
async def __ainit__(self):
await asyncio.sleep(1)
print("it works!")
# self.database = await self.client.create_database_if_not_exists("MY_DATABASE_NAME")
# self.container = await self.database.create_container_if_not_exists("MY_CONTAINER_NAME", partition_key=...)
def some_method(self):
assert self.async_initialized == True
async def main():
c = await CosmosCRUD(client=CosmosClient())
c.some_method()
cc = CosmosCRUD(client=CosmosClient())
cc.some_method() # Will fail, because it was not awaited during the instance construction
if name == "main":
asyncio.run(main())
</code></pre>