From cdbffe4252c500e63367be8a96649e03cb69a047 Mon Sep 17 00:00:00 2001 From: chang-ning Date: Mon, 13 Aug 2018 14:20:48 +0800 Subject: [PATCH] add Asynchronous Generator in typing --- docs/notes/python-typing.rst | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/docs/notes/python-typing.rst b/docs/notes/python-typing.rst index fd00dd56..12849b5c 100644 --- a/docs/notes/python-typing.rst +++ b/docs/notes/python-typing.rst @@ -171,6 +171,34 @@ Generator g: Generator = fib(10) i: Iterator[int] = (x for x in range(3)) +Asynchronous Generator +----------------------- + +.. code-block:: python + + import asyncio + + from typing import AsyncGenerator, AsyncIterator + + async def fib(n: int) -> AsyncGenerator: + a: int = 0 + b: int = 1 + while n > 0: + await asyncio.sleep(0.1) + yield a + + b, a = a + b, b + n -= 1 + + async def main() -> None: + async for f in fib(10): + print(f) + + ag: AsyncIterator = (f async for f in fib(10)) + + loop = asyncio.get_event_loop() + loop.run_until_complete(main()) + Avoid ``None`` access ----------------------