python 2 to 3 conversion

Chris Angelico rosuav at gmail.com
Mon Jun 17 10:52:13 EDT 2019


On Mon, Jun 17, 2019 at 11:15 PM Igor Korot <ikorot01 at gmail.com> wrote:
>
> Hi, Chris et al,
>
> On Mon, Jun 17, 2019 at 8:00 AM Chris Angelico <rosuav at gmail.com> wrote:
> >
> > On Mon, Jun 17, 2019 at 10:50 PM Thomas Jollans <tjol at tjol.eu> wrote:
> > >
> > > On 17/06/2019 15.14, Igor Korot 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?
> > >
> > > ‘What’s new in Python 3.0’ is a good starting point
> > >
> > > https://docs.python.org/3/whatsnew/3.0.html
> > >
> > > It doesn’t list all standard library changes, but it has the most
> > > important ones. Obviously it can't include anything that third-party
> > > modules do.
> > >
> > > The main incompatibility is obviously strings, and there various modules
> > > have adopted different strategies for the transition.
> >
> > Unfortunately starting there means ignoring all the compatibilities
> > that were implemented in more recent versions. Notably, Python 3.3
> > introduced u"..." literals, and 3.5 allows you to use percent
> > interpolation with bytes as well as text. So those kinds of
> > differences are no longer significant.
> >
> > ChrisA
>
> This is what I have in my script (reproduction steps):
>
> igor at IgorReinCloud ~/dbhandler/libdbwindow/res/gui $ python
> Python 3.6.5 (default, Oct  5 2018, 14:32:41)
> [GCC 7.3.0] on linux
> Type "help", "copyright", "credits" or "license" for more information.
> >>> import array
> >>> bytes = array.array('B', open("bold.png", "rb").read())
> >>> bytes[0:16].tostring()
> b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR'
> >>> if bytes[0:16].tostring() != '\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR':
> ...     print("Failed")
> ...
> Failed
> >>>
>
> Do I just need to add "b" in front of the string to make it work with both?
> Or I need to check version call?
>

Yep, all you need to do is compare against a byte string. That should
be the only change needed. Currently, you're checking against a byte
string in Py2, and a text string in Py3; but the b"..." prefix will
make them consistent.

ChrisA



More information about the Python-list mailing list