pythonasync-awaitmagic-methods

How to await inside a dunder method?


I want to make an async database query and insert it inside cls.__setitem__ but of course, I can't use await inside a sync function. how can I tackle this problem?


Solution

  • Async function are really just functions that return something awaitable. Usually a Coroutine for lazy evaluation (when awaited) or a Future or Task for eager evaluation. Here is how I do my async dunder methods:

    import asyncio
    from collections.abc import Coroutine
    from typing import Any
    
    
    class Foo:
        def __getitem__(self, delay: float) -> Coroutine[Any, Any, str]:
            async def get():
                print("waiting...")
                await asyncio.sleep(delay)
                return "Hello!"
            return get()
    
    
    async def main():
        foo = Foo()
        print(await foo[1.5])
    
    asyncio.run(main())