|
46 | 46 | "BufferedReader", "BufferedWriter", "BufferedRWPair",
|
47 | 47 | "BufferedRandom", "TextIOBase", "TextIOWrapper",
|
48 | 48 | "UnsupportedOperation", "SEEK_SET", "SEEK_CUR", "SEEK_END",
|
49 |
| - "DEFAULT_BUFFER_SIZE", "text_encoding", "IncrementalNewlineDecoder"] |
| 49 | + "DEFAULT_BUFFER_SIZE", "text_encoding", "IncrementalNewlineDecoder", |
| 50 | + "Reader", "Writer"] |
50 | 51 |
|
51 | 52 |
|
52 | 53 | import _io
|
53 | 54 | import abc
|
54 | 55 |
|
| 56 | +from _collections_abc import _check_methods |
55 | 57 | from _io import (DEFAULT_BUFFER_SIZE, BlockingIOError, UnsupportedOperation,
|
56 | 58 | open, open_code, FileIO, BytesIO, StringIO, BufferedReader,
|
57 | 59 | BufferedWriter, BufferedRWPair, BufferedRandom,
|
@@ -97,3 +99,55 @@ class TextIOBase(_io._TextIOBase, IOBase):
|
97 | 99 | pass
|
98 | 100 | else:
|
99 | 101 | RawIOBase.register(_WindowsConsoleIO)
|
| 102 | + |
| 103 | +# |
| 104 | +# Static Typing Support |
| 105 | +# |
| 106 | + |
| 107 | +GenericAlias = type(list[int]) |
| 108 | + |
| 109 | + |
| 110 | +class Reader(metaclass=abc.ABCMeta): |
| 111 | + """Protocol for simple I/O reader instances. |
| 112 | +
|
| 113 | + This protocol only supports blocking I/O. |
| 114 | + """ |
| 115 | + |
| 116 | + __slots__ = () |
| 117 | + |
| 118 | + @abc.abstractmethod |
| 119 | + def read(self, size=..., /): |
| 120 | + """Read data from the input stream and return it. |
| 121 | +
|
| 122 | + If *size* is specified, at most *size* items (bytes/characters) will be |
| 123 | + read. |
| 124 | + """ |
| 125 | + |
| 126 | + @classmethod |
| 127 | + def __subclasshook__(cls, C): |
| 128 | + if cls is Reader: |
| 129 | + return _check_methods(C, "read") |
| 130 | + return NotImplemented |
| 131 | + |
| 132 | + __class_getitem__ = classmethod(GenericAlias) |
| 133 | + |
| 134 | + |
| 135 | +class Writer(metaclass=abc.ABCMeta): |
| 136 | + """Protocol for simple I/O writer instances. |
| 137 | +
|
| 138 | + This protocol only supports blocking I/O. |
| 139 | + """ |
| 140 | + |
| 141 | + __slots__ = () |
| 142 | + |
| 143 | + @abc.abstractmethod |
| 144 | + def write(self, data, /): |
| 145 | + """Write *data* to the output stream and return the number of items written.""" |
| 146 | + |
| 147 | + @classmethod |
| 148 | + def __subclasshook__(cls, C): |
| 149 | + if cls is Writer: |
| 150 | + return _check_methods(C, "write") |
| 151 | + return NotImplemented |
| 152 | + |
| 153 | + __class_getitem__ = classmethod(GenericAlias) |
0 commit comments