支持python 2和3:str,bytes或alternative

sle*_*ica 7 python python-2.7 python-3.x

我有一个Python2代码库,它广泛用于str存储原始二进制数据.我想支持Python2和Python3.

Python2和Python3中的bytes(alis of str)类型bytes完全不同.它们采用不同的参数来构造,索引到不同的类型并且具有不同的strrepr.

统一两个Python版本的代码的最佳方法是什么,使用单一类型来存储原始数据?

Mis*_*agi 3

python-future包具有Python3 字节类型的向后移植。

>>> from builtins import bytes  # in py2, this picks up the backport
>>> b = bytes(b'ABCD')
Run Code Online (Sandbox Code Playgroud)

这在Python 2和Python 3中都提供了Python 3接口。在Python 3中,它是内置bytes类型。在 Python 2 中,它是类型之上的兼容层str