result icon indicating copy to clipboard operation
result copied to clipboard

Using async decorator uses type hints incompatable with with `asyncio.run` or `asyncio.create_task`

Open kalebo opened this issue 1 year ago • 2 comments

It would be nice to be able to use this with asyncio methods like run and create_task without needing to resort to escape hatches like typing.cast or #type: ignore. I'm not sure that is just having a result.as_coroutine_result or there's a better way.

An example case is the following:

from result import as_async_result
import random
import asyncio

@as_async_result(Exception)
async def example() -> str:
    if random.random() < 0.5:
        raise RuntimeError("Boom")
    return "made it"

task: str = asyncio.run( example() )
print(task)

Running mypy on that will produce the following error:

error: Argument 1 to "run" has incompatible type "Awaitable[Ok[str] | Err[Exception]]"; expected "Coroutine[Any, Any, Never]"

kalebo avatar Apr 19 '24 19:04 kalebo

This function

async def awaiting(awaitable: Awaitable[T]) -> T:
    return await awaitable

can do the trick to wrap awaitables into coroutines; alas, there is an additional await added.

nekitdev avatar Apr 23 '24 18:04 nekitdev

What would be the reason for using Awaitable instead of Coroutine then? From what I can understand, Coroutines are defined using the async def, which I assume is the use-case for the async_as_result?

Awaitable is just a less specific type used for Coroutine, Future and Task.

I tried to locally change from Awaitable to Coroutine in the result-package in my use-case and mypy was happy.

golgor avatar Jul 07 '24 11:07 golgor