osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Python 3.2 has some deadly infection


On Thu, 05 Jun 2014 23:21:35 +0300, Marko Rauhamaa wrote:

> Terry Reedy <tjreedy at udel.edu>:
> 
>> On 6/5/2014 5:53 AM, Marko Rauhamaa wrote:
>>> Chris Angelico <rosuav at gmail.com>:
>>>
>>>> If the standard streams are so crucial, why are their most obvious
>>>> interfaces insignificant to you?
>>>
>>> I want the standard streams to consume and produce bytes.
>>
>> Easy. Read the manual entry for stdxxx. "To write or read binary data
>> from/to the standard streams, use the underlying binary buffer object.
>> For example, to write bytes to stdout, use
>> sys.stdout.buffer.write(b'abc')"
> 
> This note from the manual is a bit vague:
> 
>    Note that the streams can be replaced with objects (like io.StringIO)
>    that do not support the buffer attribute or the detach() method
> 
> "Can be replaced" by who? By the Python developers? By me? By random
> library calls?

By you. sys.stdout and friends are writable. Any code you call may have 
replaced them with another file-like object, and you should honour that.

The API could have/should have been a little more friendly, but it's 
conceptually simple:

* Does sys.stdout have a buffer attribute? Then write raw bytes to
  the buffer.

* If not, then write raw bytes to sys.stdout.

* If either fails, then somebody has replaced stdout with something
  weird, and they deserve whatever horrible fate their damn fool
  move causes. It's not your responsibility to try to keep your
  application running under bizarre circumstances.



-- 
Steven D'Aprano
http://import-that.dreamwidth.org/