python 3, subclassing TextIOWrapper.

Scott David Daniels Scott.Daniels at Acm.Org
Sun Mar 22 20:03:38 EDT 2009


Gabriel Genellina wrote:
> En Sun, 22 Mar 2009 19:12:13 -0300, Benjamin Peterson 
> <benjamin at python.org> escribió:
>> Gabriel Genellina <gagsl-py2 <at> yahoo.com.ar> writes:
>>> The undocumented behavior is relying on the open() builtin to return a
>>> BufferedReader for a binary file.
>>
>> I don't see the problem. open() will return some BufferedIOBase 
>> implmentor, and
>> that's all that TextIOWrapper needs.
 >
> How do you know? AFAIK, the return value of open() is completely 
> undocumented:
> http://docs.python.org/3.0/library/functions.html#open
> And if you open the  file in text mode, the return value isn't a 
> BufferedIOBase.

OK, it is documented, but not so clearly.  I went first to the io
module, rather than the open function documentation, and looked at
what io.TextIOWrapper should get ast its first arg:

     The io module provides the Python interfaces to stream handling. The
     builtin open() function is defined in this module....

    class io.TextIOWrapper(buffer[, encoding[, errors[, newline[,
                                              line_buffering]]]])
     A buffered text stream over a BufferedIOBase raw stream, buffer....

So, we need a BufferedIOBase constructor.  Back at the introduction to
the io module, we see:
     BufferedIOBase deals with buffering on a raw byte stream
     (RawIOBase). Its subclasses, BufferedWriter, BufferedReader, and
     BufferedRWPair buffer streams that are readable, writable, and both
     readable and writable. BufferedRandom provides a buffered interface
     to random access streams. BytesIO is a simple stream of in-memory
     bytes.

In the Buffered Streams section:
     class io.BufferedIOBase
         Base class for streams that support buffering. It inherits
         IOBase.  There is no public constructor.

OK, that was daunting.
But back in the io.open description, some ways down, we read:
     The type of file object returned by the open() function depends on
     the mode. When open() is used to open a file in a text mode ('w',
     'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to
     open a file in a binary mode, the returned class varies: in read
     binary mode, it returns a BufferedReader; in write binary and append
     binary modes, it returns a BufferedWriter, and in read/write mode,
     it returns a BufferedRandom.

Aha! it is documented.  If you have some good ideas on how to make
this more obvious, I'm sure we'd be happy to "fix" the documentation.

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list