6

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?

oblalex
  • 5,366
  • 2
  • 24
  • 25

2 Answers2

3

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

oblalex
  • 5,366
  • 2
  • 24
  • 25
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.

Yuval Pruss
  • 8,716
  • 15
  • 42
  • 67
  • As for a type of the function, yes, that's true. But question was only about function's return type. Anyway, thank you – oblalex Jul 17 '17 at 17:39