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?
x is Python 3.0 which was released in 2008. The latest stable version is Python 3.9 which was released in 2020. The nature of python 3 is that the changes made in python 3 make it incompatible with python 2. So it is backward incompatible and code written in python 3 will not work on python 2 without modifications.
Basically, developers deliberately made python 3 not backwards compatible, for two main reasons: First of all, they wanted to change some things integral to python 2, and while the differences seemed small, the improvements that they had made would not have combined well with the existing structure.
Unicode (UTF-8) is a default encoding source for python 3, and str represented as length 1 string. In python 2, str is represented as the length 8-bit string. In Python 3, Syntax changes are done to make the programming language more effective and easy for the developers compared to Python 2.
If you want to determine whether Python2 or Python3 is running, you can check the major version with this sys. version_info. major . 2 means Python2, and 3 means Python3.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With