如何在Python2&;中获得兼容的type()行为;3与unicode_文字?

如何在Python2&;中获得兼容的type()行为;3与unicode_文字?,python,python-2.7,python-unicode,python-3.6,Python,Python 2.7,Python Unicode,Python 3.6,这个问题看起来非常类似,但是评论中的建议(不再适用?)如下所示 我正在尝试编写一个与python2-3兼容的包,我的一个方法中有一个类生成器,type() 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

这个问题看起来非常类似,但是评论中的建议(不再适用?)如下所示

我正在尝试编写一个与python2-3兼容的包,我的一个方法中有一个类生成器,
type()

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-2.6时代提出的,从那时起,行为似乎发生了变化。我不认为我可以直接转储unicode文本,因为如果我没有它,我会在调用hashlib时遇到可移植性问题(其他地方)。

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

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

为什么要导入unicode\u文本?这似乎是问题多于解决方案,对于这个特定的示例,您不需要它来同时在py2和Py3中工作,除非您正在执行一些需要区分字节字符串和unicode字符串的字符串操作,和/或您正在执行解码和编码等,那么您很可能不需要unicode_-literal,保持原样,它在py2和py3I中就可以正常工作。我不能保证传递到此库的字符串永远不会是Unicode。还有一些方法明确要求Unicode字符串。似乎在2-3代码中处理这个问题的推荐方法是使用unicode_文本。看起来我实际上需要混合使用这个和内置的.str()。。。在我的代码中的大多数地方,我需要builtins.str()的Python3兼容行为(例如,对于unicode文本,期望issubclass(x,str)返回True),然后对于一些极少数的特定情况(例如type()),我需要uuu builtin\uuuuu.str()。这看起来对吗?@mpunset:当然,你所需要做的就是通过给它们分配不同的名称来确保它们分开。因为
future.builtins
模块是Python3
builtins
模块的一个补充,只需继续使用
from builtins import str
,但使用
try..importorror
import。。as…
以不同的名称保持对Python2
str
对象的访问。
>>> from __future__ import unicode_literals
>>> type(str('MyClass'), (object,), {})
<class '__main__.MyClass'>
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,), {})