我在調用type()
時遇到了支持python2和python3的問題。這說明問題:unicode_literals和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
這與Any gotchas using unicode_literals in Python 2.6?。在那個問題中,有人建議類似字符串,所以天真地我想過使用six.b()
:
一個「假」字節文字。數據應該始終是一個普通的字符串文字。 在Python 2中,b()返回一個8位字符串。在Python 3中,數據編碼爲 ,拉丁字母-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
如此看來,真的,type()
想要一個python2 STR這是python2上的一個python3字符串,但它需要一個python3 str,它是python3上的一個python2 unicode字符串。
您認爲如何?
有什麼我不明白的嗎?
還是在Python 2和3上與type()
存在真正的不兼容?
是不是有任何有同樣的方法type()
呼叫同時支持2和3?
在這種情況下,six
這樣的工具不應該提供圍繞type()
的包裝嗎?
'type(str(name)'? – georg
謝謝,這是有效的,我確信我已經測試過它... – jpic