Python 2 ‘print’, coercing arguments to Unicode

Ben Finney ben+python at benfinney.id.au
Tue Oct 6 05:51:51 EDT 2015


Howdy all,

In Python 2.7, I am seeing this behaviour for ‘print’::

    Python 2.7.10 (default, Sep 13 2015, 20:30:50)
    [GCC 5.2.1 20150911] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> from __future__ import unicode_literals
    >>> from __future__ import print_function
    >>> import io
    >>> print(None)
    None
    >>> print(None, file=io.StringIO())
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: unicode argument expected, got 'str'

So, although my string literals are now Unicode objects, apparently
‘print’ still coerces objects using the bytes type ‘str’.

Binding the ‘str’ name to the Unicode type doesn't help::

    >>> str = unicode
    >>> print(None, file=io.StringIO())
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: unicode argument expected, got 'str'

The reason I need to do this is that I'm replacing the standard streams
(‘sys.stderr’, etc.) with ‘io.StringIO’ instances in a test suite. That
works great for everything but ‘print’.

Since this is a test suite for existing code, I don't have the option to
change all the existing statements; I need them to work as-is.

How can I convince ‘print’, everywhere throughout a module, that it
should coerce its arguments using ‘unicode’?

-- 
 \      “Not using Microsoft products is like being a non-smoker 40 or |
  `\     50 years ago: You can choose not to smoke, yourself, but it's |
_o__)               hard to avoid second-hand smoke.” —Michael Tiemann |
Ben Finney




More information about the Python-list mailing list