From 8a23e660727425c26a910290f5306c4936ce3a3b Mon Sep 17 00:00:00 2001 From: chang-ning Date: Mon, 13 Aug 2018 14:50:36 +0800 Subject: [PATCH] add Contents Manager in typing --- docs/notes/python-typing.rst | 45 ++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/docs/notes/python-typing.rst b/docs/notes/python-typing.rst index 12849b5c..53bd9773 100644 --- a/docs/notes/python-typing.rst +++ b/docs/notes/python-typing.rst @@ -199,6 +199,51 @@ Asynchronous Generator loop = asyncio.get_event_loop() loop.run_until_complete(main()) +Context Manager +--------------- + +.. code-block:: python + + from typing import ContextManager, Generator, IO + from contextlib import contextmanager + + @contextmanager + def open_file(name: str) -> Generator: + f = open(name) + yield f + f.close() + + cm: ContextManager[IO] = open_file(__file__) + with cm as f: + print(f.read()) + +Asynchronous Contents Manager +----------------------------- + +.. code-block:: python + + import asyncio + + from typing import AsyncContextManager, AsyncGenerator, IO + from contextlib import asynccontextmanager + + # need python 3.7 or above + @asynccontextmanager + async def open_file(name: str) -> AsyncGenerator: + await asyncio.sleep(0.1) + f = open(name) + yield f + await asyncio.sleep(0.1) + f.close() + + async def main() -> None: + acm: AsyncContextManager[IO] = open_file(__file__) + async with acm as f: + print(f.read()) + + loop = asyncio.get_event_loop() + loop.run_until_complete(main()) + Avoid ``None`` access ----------------------