79269504

Date: 2024-12-10 19:25:49
Score: 1
Natty:
Report link

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!

Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • User mentioned (1): @artem-selivanov's
  • Low reputation (1):
Posted by: Graeme Holliday