通話での 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 を使用する場合の注意事項に関連していますか? . その質問では、誰かがバイト文字列への型キャストを推奨しているので、単純に を使用することを考えましたsix.b()
:
「偽の」バイトリテラル。data は常に通常の文字列リテラルでなければなりません。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
したがって、実際にtype()
は、python2のpython3バイト文字列であるpython2 strが必要なようですが、python3のpython2 unicode文字列であるpython3 strが必要です。
どう思いますか ?
わからないことがありますか?
type()
または、Python 2 および 3との実際の非互換性はありますか?
同じ呼び出しで 2 と 3 の両方をサポートする方法はありませんか?type()
six
その場合、ラッパーを提供するようなツールはありませんtype()
か?