在 Python 2/3 中打印浮动到 io.StringIO

printing floats to io.StringIO in Python 2/3

我正在尝试编写一个在 Python 2.7 和 Python 3.* 中都有效的 Python 程序。我有一个案例,我使用 StringIO,根据 Python-Future's cheatsheet on StringIO,我所要做的就是使用 Python 3-style io 模块。

问题是我 printing floats 这个 StringIO:

from __future__ import print_function
from io import StringIO

with StringIO() as file:
    print(1.0, file=file)

这导致

TypeError: string argument expected, got 'str'

当我将 1.0 替换为 u"AAAA"(或启用 unicode_literals"AAAA")时,它工作正常。

我尝试过的替代方案:

还有其他选择吗?

这就是我处理这个问题的方法:

import sys

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

顺便说一下,这破坏了 PEP008(imports 应该在文件的顶部),但我个人认为这是合理的。