python python-2.7 stringio
Updated Sun, 03 Jul 2022 21:21:05 GMT

printing floats to io.StringIO in Python 2/3

I'm trying to write a Python program that works in both Python 2.7 and Python 3.*. I have a case where I use StringIO, and according to Python-Future's cheatsheet on StringIO, all I have to to is to use the Python 3-style io module.

The problem is that I'm printing floats to this StringIO:

from __future__ import print_function
from io import StringIO
with StringIO() as file:
    print(1.0, file=file)

This results in

TypeError: string argument expected, got 'str'

When I replace 1.0 by u"AAAA" (or "AAAA" with unicode_literals enabled), it works fine.

Alternatives I've tried:

  • BytesIO. I can't print anymore, because "unicode doesn't support the buffer interface".
  • "{:f}".format(...) every float. This is possible, but cumbersome.
  • file.write(...) instead of print(..., file=file). This works, but at this point, I don't see what the use of print() is anymore.

Are there any other options?


This is what I do with this issue:

import sys
if sys.version_info[0] == 2:  # Not named on 2.6
    from __future__ import print_function
    from StringIO import StringIO
    from io import StringIO

This breaks PEP008 by the way (imports should be at the top of the file), but personally I think it is justified.

Comments (2)

External Links

External links referenced by this document: