Search code examples
pythonpython-2.7python-3.xpypi

What is a good way to support Python 2 in a Python 3 codebase when using PyPi?


I've written a library in Python 3 and recently a pull request came in that added support for Python 2.7. The pull request is this: https://github.com/JelteF/PyLaTeX/pull/9.

What it basically does is adding some import fixs and making the super calls explicit. I have mixed feelings about this, since one of the big reasons I chose for python 3 was the cleaner syntax and this makes it compatible by using the 'ugly' syntax. However, I do like that people stuck with Python 2 can use the library as well.

This is why I was thinking about separate codebases for python2 and python3. Is there a way to set PyPi up so that it uses a separate codebase different versions of Python? Using separate branches would be preferable, since merging new changes would be easy in that case.

Or is there some better option that I'm overlooking?


Solution

  • I've just released my library for Python 2.7 as well. The way I did is is to use the 3to2 and compile the Python 3 code to 2.7 code before uploading it to PyPi.

    mkdir -p python2_source
    cp -R pylatex tests examples python2_source
    3to2 python2_source -wn -f collections -f all
    

    You also have to add python2_source to MANIFEST.in, so it will be in your distributed files. Then I have this small piece of code in my setup.py to install from the python2_source folder if the setup is done using Python 2.7.

    if sys.version_info[0] == 3:
        source_dir = '.'
    else:
        source_dir = 'python2_source'
    

    and then have package_dir={'': source_dir} in the actual setup call.