From 014a869a2ae07af9a6a209422c260c198c21cf27 Mon Sep 17 00:00:00 2001 From: Guido van Rossum Date: Tue, 24 May 2016 12:18:54 -0700 Subject: [PATCH] Short subsection on annotating coroutines (Ivan L, #225). --- pep-0484.txt | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/pep-0484.txt b/pep-0484.txt index 01957bed1..781e23ef7 100644 --- a/pep-0484.txt +++ b/pep-0484.txt @@ -1015,6 +1015,40 @@ In such cases the default value may be specified as a literal ellipsis, i.e. the above example is literally what you would write. +Annotating generator functions and coroutines +--------------------------------------------- + +The return type of generator functions can be annotated by +the generic type ``Generator[yield_type, send_type, +return_type]`` provided by ``typing.py`` module:: + + def echo_round() -> Generator[int, float, str]: + res = yield + while res: + res = yield round(res) + return 'OK' + +Coroutines introduced in PEP 492 are annotated with the same syntax as +ordinary functions. However, the return type annotation corresponds to the +type of ``await`` expression, not to the coroutine type:: + + async def spam(ignored: int) -> str: + return 'spam' + + async def foo(): + bar = await spam(42) # type: str + +The ``typing.py`` module also provides generic ABCs ``Awaitable``, +``AsyncIterable``, and ``AsyncIterator`` for situations where more precise +types cannot be specified:: + + def op() -> typing.Awaitable[str]: + if cond: + return spam(42) + else: + return asyncio.Future(...) + + Compatibility with other uses of function annotations =====================================================