osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

python 2 to 3 conversion


Hi, Chris,

On Mon, Jun 17, 2019 at 7:31 AM Chris Angelico <rosuav at gmail.com> wrote:
>
> 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.

        bytes = array.array('B', open(path, "rb").read())
        count = len(bytes)

This is where bytes come from - sorry about that.

So, how do I write the code compatible with both python 2 and python 3
in this case?

Thank you.

>
> 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
> --
> https://mail.python.org/mailman/listinfo/python-list