Python Glossary Русский

Python 3.5+typingterm

typing.IO

I/O streams

A generic type of file objects (streams) for annotations; parameterized by the element type (str or bytes).

Syntax

def f(stream: typing.IO[str]) -> None: ...

In practice people reach for the specialized TextIO and BinaryIO instead of IO[str]/IO[bytes] — the same streams but with extra members (encoding, buffer, and so on) and a clearer name. IO itself is for parameters that only care that something is a stream regardless of its concrete class — an open() result, io.StringIO, a socket wrapper.

Examples

from typing import IO
import io
print(IO.__name__)   # → IO
print(IO[str])   # → typing.IO[str]
from typing import IO
import io
def read_all(stream: IO[str]) -> str: return stream.read()
print(read_all(io.StringIO('hello world')))   # → hello world
print(isinstance(io.StringIO(), IO))   # → False

See also

Open in the full glossarydocs.python.orgReport an inaccuracy