From aa4315c1bb3fb0dbde540373398d7421e705aafa Mon Sep 17 00:00:00 2001 From: Sebastian Rittau Date: Tue, 17 May 2022 13:06:24 +0200 Subject: [PATCH 1/2] Advise to use typing.IO sparingly Closes: #92877 --- Doc/library/typing.rst | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/Doc/library/typing.rst b/Doc/library/typing.rst index 29bcedaddce9dd..27d11b79783283 100644 --- a/Doc/library/typing.rst +++ b/Doc/library/typing.rst @@ -1940,6 +1940,25 @@ Other concrete types represent the types of I/O streams such as returned by :func:`open`. + These types should be used sparingly. For argument types, a tight + :class:`Protocol` that documents the actual needs of the implementation + is often a better alternative. Return values should be annotated with + the actual concrete type returned. For example:: + + from io import StringIO + + class Reader(Protocol): + def read(self, __size: int) -> bytes: ... + def close(self) -> object: ... + + def to_text_stream(stream: Reader) -> StringIO: + s_io = StringIO() + while b := stream.read(1000): + s_io.write(b.decode("ascii")) + stream.close() + s_io.seek(0) + return s_io + .. deprecated-removed:: 3.8 3.12 The ``typing.io`` namespace is deprecated and will be removed. These types should be directly imported from ``typing`` instead. From 4a5a9a4c6cabc9902f02726f12f57d807e974dc3 Mon Sep 17 00:00:00 2001 From: Sebastian Rittau Date: Tue, 17 May 2022 15:15:06 +0200 Subject: [PATCH 2/2] Use standard positional-only syntax. Co-authored-by: Jelle Zijlstra --- Doc/library/typing.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Doc/library/typing.rst b/Doc/library/typing.rst index 27d11b79783283..bdaeba7a8a825f 100644 --- a/Doc/library/typing.rst +++ b/Doc/library/typing.rst @@ -1948,7 +1948,7 @@ Other concrete types from io import StringIO class Reader(Protocol): - def read(self, __size: int) -> bytes: ... + def read(self, size: int, /) -> bytes: ... def close(self) -> object: ... def to_text_stream(stream: Reader) -> StringIO: