Mailing List Archive

io.TextIOWrapper and io.RawIOBase
Documentation for `io.TextIOWrapper` [[1]] suggests that the buffer
supplied to the constructor should be of `io.BufferedIOBase` type:

> A buffered text stream over a `BufferedIOBase` binary stream.

Looking at the implementation of `io.TextIOWrapper` in both
`Modules/_io/textio.c` [[2]] and `Lib/_pyio.py` [[3]], it seems like
`io.TextIOWrapper` will only use the following attributes and functions
on the supplied `buffer` object:

```python
buffer.closed
buffer.close()
buffer._dealloc_warn()
# ^ only from Modules/_io/textio.c, looks like failures will be ignored
buffer.fileno()
buffer.flush()
buffer.isatty()
buffer.name
# ^ only when TextIOWrapper.buffer is accessed
buffer.raw()
# ^ only if buffer is instance of BufferedReader, BufferedWriter
# or BufferedRandom, also only from Modules/_io/textio.c
buffer.read()
buffer.read1() # only if buffer has a read1 method
buffer.readable()
buffer.seek()
buffer.seekable()
buffer.tell()
buffer.truncate()
buffer.writable()
buffer.write()
```

More specifically, `io.TextIOWrapper` looks like it will work fine with
`buffer` objects that does not have any of the following attributes and
methods that only exists in `io.BufferedIOBase`, but not in
`io.RawIOBase`:

```python
buffer.raw
# ^ this is only called if buffer is an instance of
# explicit subclasses of `io.BufferedIOBase`
buffer.detatch() # this is never called
buffer.read1() # this is only used if it exists
buffer.readinto() # this is never called
buffer.readinto1() # this is never called
```

Or stated differently, it looks like `io.TextIOWrapper` will work
equally well with buffer objects that are either `io.RawIOBase` or
`io.BufferedIOBase` types.

So the question is, if my assessment is correct, should the
documentation not be updated to clearly state that the `buffer` can be
either a `io.RawIOBase` or `io.BufferedIOBase` object?

(text written for python 3.7.12)

[1]: https://docs.python.org/3.7/library/io.html#io.TextIOWrapper
[2]: https://github.com/python/cpython/blob/v3.7.12/Modules/_io/textio.c
[3]: https://github.com/python/cpython/blob/v3.7.12/Lib/_pyio.py
--
https://mail.python.org/mailman/listinfo/python-list