3

Let's say you need to write binary data to standard output:

sys.stdout.buffer.write(data)

Then to flush it you can use either of these two:

sys.stdout.flush()
sys.stdout.buffer.flush()

Both of these two calls seem to work the same way in a simple situation. However:

  • the first one calls flush on the whole stdout object (_io.TextIOWrapper)

  • the second one calls flush only on the buffer sub-object (_io.BufferedWriter).

What are the situations where one would prefer one over the other?

1 Answer 1

3

Fundamentally the difference between the TextIOWrapper and BufferedWriter is what they are designed to process. Having a look at the Python documentation you'll see that BufferedWriter is designed to handle byte streams:

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.

While the TextIOWrapper is designed to handle byte-streams that are specific to text, handling things like encoding and decoding.

Another IOBase subclass, TextIOBase, deals with streams whose bytes represent text, and handles encoding and decoding from and to unicode strings. TextIOWrapper, which extends it, is a buffered text interface to a buffered raw stream (BufferedIOBase).

As for which one you should be calling flush on. It's a wash since the TextIOWrapper is actually just a nice wrapper for text BufferedIOBase. So if, as you say, you are actually handling binary data and not text-based data, then you could just use the BufferedIOBase.

Sign up to request clarification or add additional context in comments.

2 Comments

Can you provide an example of how to use BufferedIOBase in place of sys.stdout.buffer for a more complete answer? (I.e. does one have to create a new object, what are the arguments, etc.)
I think I have answered the question you asked reasonably. If you wanted to know how to use the BufferedIOBase class you could always look at resources like these

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.