python - 如何使用 unicode_literals 在 python 2 和 3 中获得兼容的 type() 行为?

标签 python python-2.7 python-unicode python-3.6

这个问题看起来与 this one 惊人地相似,但是评论中的建议不起作用(不再?),如下所示。

我正在尝试编写一个 python2-3 兼容包,我的一个方法中有一个类生成器,type() 在 python-2.7 测试中给我带来了问题:

Python 2.7.13 (default, Mar 18 2017, 17:03:32) 
[GCC 4.2.1 Compatible Apple LLVM 7.0.2 (clang-700.1.81)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from __future__ import unicode_literals
>>> from builtins import str
>>> type('MyClass', (object,), {})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: type() argument 1 must be string, not unicode
>>> type(str('MyClass'), (object,), {})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: type() argument 1 must be string, not newstr

Python-Future overview页面说:

# Compatible output from isinstance() across Py2/3:
assert isinstance(2**64, int)        # long integers
assert isinstance(u'blah', str)
assert isinstance('blah', str)       # only if unicode_literals is in effect

我预计这会在任何需要字符串的地方给我一致的行为,但显然不是。

正确的、与版本无关的方法是什么?我链接到的另一个问题是在 python-2.6 时代提出的,从那时起行为似乎发生了变化。我不认为我可以只转储 unicode_literals,因为如果我没有 hashlib,我会在调用 hashlib 时遇到可移植性问题(在其他地方)。

最佳答案

不要使用 builtins.str(),使用 Python 版本附带的普通 str:

>>> from __future__ import unicode_literals
>>> type(str('MyClass'), (object,), {})
<class '__main__.MyClass'>

这在 Python 2 和 3 中都有效。如果 future.builtins 模块默认替换 str 内置类型,请使用 __builtin__模块:

try:
    # Python 2
    from __builtin__ import str as builtin_str
except ImportError:
    # Python 3
    from builtins import str as builtin_str

MyClass = type(builtin_str('MyClass'), (object,), {})

关于python - 如何使用 unicode_literals 在 python 2 和 3 中获得兼容的 type() 行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42940967/

相关文章:

python - 具有一对多关系的 Django Form

python - 基于列表元素和列表值的字典键

python - 压缩文件解压缩时出现 unicode 错误

numpy - 类型错误 : ufunc 'subtract' did not contain a loop with signature matching types dtype ('<U1' ) dtype ('<U1' ) dtype ('<U1' )

Python unicode 转义下划线和双引号

python - 从 GLCM 中提取 Haralick 特征。为什么我会为每个功能获取多个值?

python - 关于 Arm 处理器上的 conda 发行版/ channel 的困惑

javascript - Django - 查询集索引而不是循环

python - 删除具有少量列的重复项并对其他列求和

google-app-engine - Google App Engine 上的 SSL 证书