python 2 to 3 conversion

Grant Edwards grant.b.edwards at gmail.com
Mon Jun 17 10:29:59 EDT 2019


On 2019-06-17, Igor Korot <ikorot01 at gmail.com> wrote:

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

Writing 2/3 compatible code that deals with bytes is difficult.  For example:

    Python 2.7.15 (default, Sep 12 2018, 15:19:18)

    >>> bytes(5)
    '5'
    >>> b'1234'[0]
    '1'


    Python 3.7.3 (default, May 20 2019, 15:21:07)

    >>> bytes(5)
    b'\x00\x00\x00\x00\x00'
    >>> b'1234'[0]
    49
    
Differences like those mean you can't really use the bytes type/class
or indexing of bytes objects in code that needs to be 2/3 compatible.

I tried writing a bytes class for 2.7, but gave up.

In anything dealing with bytes, trying to be compatible with 2 and 3
is a lot of work, and I usually don't bother.

-- 
Grant Edwards               grant.b.edwards        Yow! I guess you guys got
                                  at               BIG MUSCLES from doing too
                              gmail.com            much STUDYING!




More information about the Python-list mailing list