Supporting Python 2 And 3: Str, Bytes Or Alternative

- 1 answer

I have a Python2 codebase that makes extensive use of str to store raw binary data. I want to support both Python2 and Python3.

The bytes (an alis of str) type in Python2 and bytes in Python3 are completely different. They take different arguments to construct, index to different types and have different str and repr.

What's the best way of unifying the code for both Python versions, using a single type to store raw data?



The python-future package has a backport of the Python3 bytes type.

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

This provides the Python 3 interface in both Python 2 and Python 3. In Python 3, it is the builtin bytes type. In Python 2, it is a compatibility layer on top of the str type.