Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Supporting python 2 and 3: str, bytes or alternative

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?

like image 860
slezica Avatar asked Mar 11 '16 14:03

slezica


People also ask

Are Python 2 and 3 compatible with each other?

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.

Why are Python 2 and 3 not compatible?

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.

What is the difference between text encoding in Python 2 and Python 3?

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.

How do I know if my code is Python2 or Python3?

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.


1 Answers

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.

like image 86
MisterMiyagi Avatar answered Nov 03 '22 09:11

MisterMiyagi