Created
March 18, 2025 00:56
-
-
Save Graeme22/b8807e159ca1be29804bd2e66602abff to your computer and use it in GitHub Desktop.
Python async constructor (via __await__)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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