From 43a554bb4e6cde485a2845cabade9fbb786edc8f Mon Sep 17 00:00:00 2001 From: Ivan Levkivskyi Date: Tue, 24 May 2016 10:46:51 +0200 Subject: [PATCH 1/2] Short subsection on annotating coroutines --- pep-0484.txt | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/pep-0484.txt b/pep-0484.txt index 01957bed..681d111d 100644 --- a/pep-0484.txt +++ b/pep-0484.txt @@ -1015,6 +1015,39 @@ 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`` 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 ===================================================== From 30ec2751a96be037a02879b6c551b7a00d05a596 Mon Sep 17 00:00:00 2001 From: Ivan Levkivskyi Date: Tue, 24 May 2016 20:21:18 +0200 Subject: [PATCH 2/2] response to comments: clarify Generator params --- pep-0484.txt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pep-0484.txt b/pep-0484.txt index 681d111d..781e23ef 100644 --- a/pep-0484.txt +++ b/pep-0484.txt @@ -1019,7 +1019,8 @@ Annotating generator functions and coroutines --------------------------------------------- The return type of generator functions can be annotated by -the generic type ``Generator`` provided by ``typing.py`` module:: +the generic type ``Generator[yield_type, send_type, +return_type]`` provided by ``typing.py`` module:: def echo_round() -> Generator[int, float, str]: res = yield