Skip to content

Commit aa4315c

Browse files
committed
Advise to use typing.IO sparingly
Closes: python#92877
1 parent 702e0da commit aa4315c

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

Doc/library/typing.rst

+19
Original file line numberDiff line numberDiff line change
@@ -1940,6 +1940,25 @@ Other concrete types
19401940
represent the types of I/O streams such as returned by
19411941
:func:`open`.
19421942

1943+
These types should be used sparingly. For argument types, a tight
1944+
:class:`Protocol` that documents the actual needs of the implementation
1945+
is often a better alternative. Return values should be annotated with
1946+
the actual concrete type returned. For example::
1947+
1948+
from io import StringIO
1949+
1950+
class Reader(Protocol):
1951+
def read(self, __size: int) -> bytes: ...
1952+
def close(self) -> object: ...
1953+
1954+
def to_text_stream(stream: Reader) -> StringIO:
1955+
s_io = StringIO()
1956+
while b := stream.read(1000):
1957+
s_io.write(b.decode("ascii"))
1958+
stream.close()
1959+
s_io.seek(0)
1960+
return s_io
1961+
19431962
.. deprecated-removed:: 3.8 3.12
19441963
The ``typing.io`` namespace is deprecated and will be removed.
19451964
These types should be directly imported from ``typing`` instead.

0 commit comments

Comments
 (0)