Search code examples
pythonasynchronousasync-await

How to make a value awaitable in python?


I have an int, and I want to make it awaitable, how can I do it ?

Context : I implementing an async generator yielding awaitable objects. However, it needs to await the first (and only the first) value so that it can yield the others.

Thus, the first value is already awaited, but the other are yieleded as they are , and the caller will await them. However, I don't want to add a ifawaitable logic in the caller, here why I want to make the first value awaitable.

The first way I considered is to crate a simple async identity function, but I was wondering if such function would already exist ? (or if there were a cleaner way)

async def make_awaitable(value):
  return value

Solution

  • You can wrap it in a Future and return that, like this:

    import asyncio
    from typing import Awaitable, TypeVar
    
    T = TypeVar("T")
    
    
    def make_awaitable(value: T) -> Awaitable[T]:
        """Return an awaitable that resolves to the given value."""
        fut: asyncio.Future[T] = asyncio.Future()
        fut.set_result(value)
        return fut
    

    Since this is now a regular (non-async) function, you can inline it in your code if that makes things more readable.