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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With