|
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,49 @@ 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 | + |
| 108 | +class Reader[T](abc.ABC): |
| 109 | + """Protocol for simple I/O reader instances. |
| 110 | +
|
| 111 | + This protocol only supports blocking I/O. |
| 112 | + """ |
| 113 | + |
| 114 | + __slots__ = () |
| 115 | + |
| 116 | + @abstractmethod |
| 117 | + def read(self, size: int = ..., /) -> T: |
| 118 | + """Read data from the input stream and return it. |
| 119 | +
|
| 120 | + If "size" is specified, at most "size" items (bytes/characters) will be |
| 121 | + read. |
| 122 | + """ |
| 123 | + |
| 124 | + @classmethod |
| 125 | + def __subclasshook__(cls, C): |
| 126 | + if cls is Reader: |
| 127 | + return _check_methods(C, "read") |
| 128 | + return NotImplemented |
| 129 | + |
| 130 | + |
| 131 | +class Writer[T](abc.ABC): |
| 132 | + """Protocol for simple I/O writer instances. |
| 133 | +
|
| 134 | + This protocol only supports blocking I/O. |
| 135 | + """ |
| 136 | + |
| 137 | + __slots__ = () |
| 138 | + |
| 139 | + @abstractmethod |
| 140 | + def write(self, data: T, /) -> int: |
| 141 | + """Write data to the output stream and return number of items written.""" |
| 142 | + |
| 143 | + @classmethod |
| 144 | + def __subclasshook__(cls, C): |
| 145 | + if cls is Writer: |
| 146 | + return _check_methods(C, "write") |
| 147 | + return NotImplemented |
0 commit comments