python 2 to 3 conversion

Chris Angelico rosuav at gmail.com
Mon Jun 17 08:22:14 EDT 2019


On Mon, Jun 17, 2019 at 10:15 PM Igor Korot <ikorot01 at gmail.com> wrote:
>
> Hi,
> Is there a place where there is a full list of incompatibilities between
> python 2 and python 3 is available and how to fix them?
>
> I'm looking for a way to fix following code, which runs perfectly with python 2
> (and make it work with both python 2 and python 3):
>
> if bytes[0:16].tostring() != '<some_string>':
>
> I know there are automated tools that can help you do the upgrade, but
> automated tools can do only so much....
>
> And I am not sure if they can just add python 3 code and include version check.

If "bytes" here refers to a byte string, and not to the actual type
called "bytes" (the same as "str" in Py2), the way I'd do it is:

if bytes[:16] != b"<some_string>":

However, I have no idea what your .tostring() method is, since it
doesn't seem to be a method on the Py2 str object, nor of the
bytearray object (my next guess). So further details/context would be
needed.

I would strongly recommend requiring either Python 2.7 or Python 3.5+.
There should be no need to support Python 2.6 or older, and if you
restrict your Py3 support to 3.5 and better, you can take advantage of
a number of syntactic compatibilities - u"text" and b"ASCII bytes"
will work on both, and b"x %d y" % 1234 will have equivalent
functionality. Features like that will make it much easier to code to
the common subset.

ChrisA



More information about the Python-list mailing list