Skip to content

Instantly share code, notes, and snippets.

@Graeme22
Created March 18, 2025 00:56
Show Gist options
  • Select an option

  • Save Graeme22/b8807e159ca1be29804bd2e66602abff to your computer and use it in GitHub Desktop.

Select an option

Save Graeme22/b8807e159ca1be29804bd2e66602abff to your computer and use it in GitHub Desktop.
Python async constructor (via __await__)
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment