Here's a modified version of @artem-selivanov's answer that I think is a bit cleaner. It uses only dunder methods:
import asyncio
class AsyncObj:
def __init__(self, name):
self.name = name
async def __aenter__(self):
await asyncio.sleep(1)
print(f"Hello {self.name}!")
return self
async def __aexit__(self, *exc):
await asyncio.sleep(1)
def __await__(self):
return self.__aenter__().__await__()
obj1 = await AsyncObj("Bob")
print(obj1)
async with AsyncObj("Fred") as obj2:
print(obj2)
This makes it possible to simply await
the object and use the constructor normally, which is great!
Note that __await__
itself is NOT async, which threw me for a loop!