Python 2 and Python 3 dual development

后端 未结 5 640
暖寄归人
暖寄归人 2020-11-27 18:14

I\'m just starting a new Python project, and ideally I\'d like to offer Python 2 and 3 support from the start, with minimal developmental overhead. My question is, what is t

5条回答
  •  难免孤独
    2020-11-27 19:13

    My personal experience has been that it's easier to write code that works unchanged in both Python 2 and 3, rather than rely on 2to3/3to2 scripts which often can't quite get the translation right.

    Maybe my situation is unusual as I'm doing lots with byte types and 2to3 has a hard task converting these, but the convenience of having one code base outweighs the nastiness of having a few hacks in the code.

    As a concrete example, my bitstring module was an early convert to Python 3 and the same code is used for Python 2.6/2.7/3.x. The source is over 4000 lines of code and this is this bit I needed to get it to work for the different major versions:

    # For Python 2.x/ 3.x coexistence
    # Yes this is very very hacky.
    try:
        xrange
        for i in range(256):
            BYTE_REVERSAL_DICT[i] = chr(int("{0:08b}".format(i)[::-1], 2))
    except NameError:
        for i in range(256):
            BYTE_REVERSAL_DICT[i] = bytes([int("{0:08b}".format(i)[::-1], 2)])
        from io import IOBase as file
        xrange = range
        basestring = str
    

    OK, that's not pretty, but it means that I can write 99% of the code in good Python 2 style and all the unit tests still pass for the same code in Python 3. This route isn't for everyone, but it is an option to consider.

提交回复
热议问题