This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Confusing error message when passing bytes to print with file pointing to a binary file
Type: behavior Stage:
Components: IO Versions: Python 3.10, Python 3.9, Python 3.8
process
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: amaury.forgeotdarc, georg.brandl, pitrou, r.david.murray
Priority: low Keywords:

Created on 2009-06-18 02:51 by r.david.murray, last changed 2022-04-11 14:56 by admin.

Messages (3)
msg89490 - (view) Author: R. David Murray (r.david.murray) * (Python committer) Date: 2009-06-18 02:51
The documentation for the print function specifies that the input
argument is coerced to string.  However, if bytes are passed and the
file= parameter points to a file open for binary write, the error
message produced is:

>>> out = open('temp', 'wb')
>>> print(b'abc', file=out)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: write() argument 1 must be bytes or buffer, not str

which is, to say the least, confusing, since I clearly passed print a
bytes object as argument 1.
msg89493 - (view) Author: Georg Brandl (georg.brandl) * (Python committer) Date: 2009-06-18 07:03
How would you propose to fix this?  print() should certainly not catch
all TypeErrors and raise a new one...

Maybe exception chaining could be used, so that print raises a TypeError
of its own with the cause being the original message?
msg89725 - (view) Author: Amaury Forgeot d'Arc (amaury.forgeotdarc) * (Python committer) Date: 2009-06-26 10:56
The problem here is not the bytes object: it is correctly coerced to a
string. 

The problem is the binary stream, which cannot accept strings.
We could maybe detect common errors and add a check at the beginning of
the print() function? something like
    if isinstance(file, (BufferedWriter, RawIOBase)):
        raise ValueError("file should be a text stream")
History
Date User Action Args
2022-04-11 14:56:50adminsetgithub: 50553
2020-11-06 15:00:03iritkatrielsetstage: test needed ->
versions: + Python 3.8, Python 3.9, Python 3.10, - Python 3.2, Python 3.3
2011-11-16 11:47:17ezio.melottisetnosy: + pitrou

versions: + Python 3.3, - Python 3.1
2009-06-26 10:56:26amaury.forgeotdarcsetnosy: + amaury.forgeotdarc
messages: + msg89725
2009-06-18 07:03:40georg.brandlsetnosy: + georg.brandl
messages: + msg89493
2009-06-18 02:51:44r.david.murraycreate