我在支持 python2 和 python3 时遇到问题type()
称呼。这说明了这个问题:
from __future__ import unicode_literals
name='FooClass'
type(name, (dict,), {})
在python3上没问题,但在python2上:
Traceback (most recent call last):
File "test.py", line 6, in <module>
type(name, (dict,), {})
TypeError: type() argument 1 must be string, not unicode
这与在 Python 2.6 中使用 unicode_literals 有什么问题吗? https://stackoverflow.com/questions/809796/any-gotchas-using-unicode-literals-in-python-2-6。在这个问题中,有人建议将类型转换为字节串,所以我天真地考虑使用six.b() http://pythonhosted.org/six/#six.b:
“假”字节文字。数据应该始终是普通的字符串文字。
在 Python 2 中,b() 返回一个 8 位字符串。在Python 3中,数据被编码
使用 latin-1 编码为字节。
所以它看起来像这样:
from __future__ import unicode_literals
import six
name='FooClass'
type(six.b(name), (dict,), {})
但在 python2 和 python3 上都失败了:
$ python2 test.py
Traceback (most recent call last):
File "test.py", line 6, in <module>
type(six.b(name), (dict,), {})
TypeError: type() argument 1 must be string, not unicode
$ python3 test.py
Traceback (most recent call last):
File "test.py", line 6, in <module>
type(six.b(name), (dict,), {})
TypeError: type() argument 1 must be str, not bytes
所以看来really, type()
想要一个 python2 str,它是 python2 上的 python3 字节串,但它想要一个 python3 str,它是 python3 上的 python2 unicode 字符串。
你怎么认为 ?
有什么我不明白的吗?
或者确实存在不兼容的情况type()
在 python 2 和 3 上?
没有吗any拥有相同的方式type()
调用同时支持 2 和 3 ?
难道不应该有一个类似的工具吗?six
提供一个包装器type()
在这种情况下 ?