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
The problem is that I'm
floats to this
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
unicode_literals enabled), it works fine.
Alternatives I've tried:
BytesIO. I can't
unicodedoesn't support the buffer interface".
float. This is possible, but cumbersome.
print(..., file=file). This works, but at this point, I don't see what the use of
Are there any other options?
This is what I do with this issue:
import sys if sys.version_info == 2: # Not named on 2.6 from __future__ import print_function from StringIO import StringIO else: 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.
StringIO.StringIOdoesn't play well with
with: it doesn't implement
__exit__. For that, I'll just have to
finallyexplicitly. — Apr 18, 2016 at 15:38
External links referenced by this document: