这个问题看起来与 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
# 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/