Python typings and futures
Asked Answered
M

2

7

I'm very glad to use typing module in Python 3. Also, I'm very glad to use asyncio instead of twisted, tornado and alternatives.

My question is how to define result of a coroutine properly?

Should we tell it's just a coroutine? Example 1:

async def request() -> asyncio.Future:
    pass

Or should we define type of result of coroutine as type of returning value? Example 2:

async def request() -> int:
    pass

If yes, then how to be with plain functions, which return futures? Example 3:

def request() -> asyncio.Future:
    f = asyncio.Future()
    # Do something with the future
    return f

Is it a right way? How then we can tell what is expected to be a result of the future?

Mendelevium answered 15/7, 2017 at 7:52 Comment(5)
Use the generic versions, e.g. docs.python.org/3/library/typing.html#typing.AwaitableKreegar
Thanks, that's perfectMendelevium
This question is similar to: The right way to type hint a Coroutine function?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem.Dichotomize
Hello @InSync, thank you for the suggestion. Considering this question was asked 5 years before the one you've mentioned, I'd suggest you asking the author of that later question.Mendelevium
That question has better answers, and being older does not prevent a question from being a dupe. See Should I flag a question as duplicate if it has received better answers?.Dichotomize
M
3

As @jonrsharpe said, typing.Awaitable perfectly suits the task.

Mendelevium answered 15/7, 2017 at 16:47 Comment(0)
A
3

In general, you should regular return value (such as int, float, bool, None and etc), but if you use it as a callable it should look like this:

async def bar(x: int) -> str:
    return str(x)

cbar: Callable[[int], Awaitable[str]] = bar

For more information: here.

You can look at this issue also for mypy support.

Aspectual answered 15/7, 2017 at 19:28 Comment(1)
As for a type of the function, yes, that's true. But question was only about function's return type. Anyway, thank youMendelevium

© 2022 - 2024 — McMap. All rights reserved.