Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
kalebo opened this issue Apr 19, 2024 · 2 comments

Comments

@kalebo
Copy link

kalebo commented Apr 19, 2024

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]"
@nekitdev
Copy link

nekitdev commented Apr 23, 2024

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.

@golgor
Copy link

golgor commented Jul 7, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants