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: print_function and unicode_literals don't work together
Type: behavior Stage: needs patch
Components: Interpreter Core Versions: Python 2.7, Python 2.6
process
Status: closed Resolution: fixed
Dependencies: Superseder:
Assigned To: Nosy List: benjamin.peterson, exarkun, ezio.melotti, jszakmeister, vstinner
Priority: high Keywords:

Created on 2008-12-10 13:19 by exarkun, last changed 2022-04-11 14:56 by admin. This issue is now closed.

Messages (3)
msg77539 - (view) Author: Jean-Paul Calderone (exarkun) * (Python committer) Date: 2008-12-10 13:19
Consider:

exarkun@charm:~$ ~/Projects/python/branches/release26-maint/python 
Python 2.6+ (trunk:66997, Oct 23 2008, 16:02:09) 
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def f(o):
...     print type(o)
... 
>>> f('foo')
<type 'str'>
>>> from __future__ import unicode_literals
>>> f('foo')
<type 'unicode'>
>>> from __future__ import print_function
>>> print('foo')
foo
>>> from io import StringIO
>>> print('foo', file=StringIO())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File
"/home/exarkun/Projects/python/branches/release26-maint/Lib/io.py", line
1487, in write
    s.__class__.__name__)
TypeError: can't write str to text stream
>>> StringIO().write('foo')
3
>>> StringIO().write(b'foo')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File
"/home/exarkun/Projects/python/branches/release26-maint/Lib/io.py", line
1487, in write
    s.__class__.__name__)
TypeError: can't write str to text stream
>>>

It seems the type of a literal string is `str´ when it is an argument to
the print function, even with the unicode_literals future import in effect.
msg77540 - (view) Author: STINNER Victor (vstinner) * (Python committer) Date: 2008-12-10 13:38
The TypeError("can't write str to text stream") comes from the newline 
written by builtin_print().

Workaround: print(u"foo", end=u"\n", file=StringIO()).
msg90029 - (view) Author: Benjamin Peterson (benjamin.peterson) * (Python committer) Date: 2009-07-02 18:17
Fixed in r73776.
History
Date User Action Args
2022-04-11 14:56:42adminsetgithub: 48868
2009-07-02 18:17:22benjamin.petersonsetstatus: open -> closed

nosy: + benjamin.peterson
messages: + msg90029

resolution: fixed
2009-05-31 05:44:27ezio.melottisetnosy: + ezio.melotti
2009-05-30 21:11:42pitrousetpriority: high
stage: needs patch
type: behavior
versions: + Python 2.7
2009-05-29 10:31:37jszakmeistersetnosy: + jszakmeister
2008-12-10 13:38:18vstinnersetnosy: + vstinner
messages: + msg77540
2008-12-10 13:19:05exarkuncreate