Re: [Python-Dev] [Python-checkins] peps: Short subsection on annotating coroutines (Ivan L, #225).
On Tue, 24 May 2016 at 12:20 guido.van.rossum
https://hg.python.org/peps/rev/50c3f5aefbb7 changeset: 6341:50c3f5aefbb7 user: Guido van Rossum
date: Tue May 24 12:18:54 2016 -0700 summary: Short subsection on annotating coroutines (Ivan L, #225). files: pep-0484.txt | 34 ++++++++++++++++++++++++++++++++++ 1 files changed, 34 insertions(+), 0 deletions(-)
diff --git a/pep-0484.txt b/pep-0484.txt --- a/pep-0484.txt +++ b/pep-0484.txt @@ -1015,6 +1015,40 @@ 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
If the coroutine has multiple await expressions that return different types then do you simply use a Union to express that? -Brett
+ +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 =====================================================
-- Repository URL: https://hg.python.org/peps _______________________________________________ Python-checkins mailing list Python-checkins@python.org https://mail.python.org/mailman/listinfo/python-checkins
participants (1)
-
Brett Cannon