这个问题看起来非常类似于这一个,但是评论中的建议不再起作用了(?)如下所示。
我正在尝试编写一个兼容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 newstrPython-未来概览页面上写着:
# 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调用,就会遇到可移植性问题(其他地方)。
发布于 2017-04-10 20:36:35
不要使用builtins.str(),使用随您的Python版本附带的普通str:
>>> from __future__ import unicode_literals
>>> type(str('MyClass'), (object,), {})
<class '__main__.MyClass'>这在Python2和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,), {})https://stackoverflow.com/questions/42940967
复制相似问题