"how to organize python modules for pypi to support 2.x and 3.x" Code Answer

3

i found that setup.py for httplib2 seems to have an elegant way to support python 2.x and 3.x. so i decided to copy that method.

the task is to craft a single setup.py for the package distribution that works with all the supported python distributions. then with the same setup.py, you can do:

python2 setup.py install

as well as

python3 setup.py install

it should be possible to keep setup.py simple enough to be parsed with all the supported python distributions. i've successfully done so with a package cobs that supports 2.4 through 2.6 as well as 3.1. that package includes pure python code (separate code for python 2.x and 3.x) and c extensions, written separately for 2.x and 3.x.

to do it:

1) i put the python 2.x code into a python2 subdirectory, and python 3.x code in a python3 subdirectory.

2) i put the c extension code for 2.x and 3.x in a src directory under python2 and python3.

so, the directory structure is:

root
  |
  +--python2
  |     |
  |     +--src
  |
  +--python3
  |     |
  |     +--src
  |
  +--setup.py
  +--manifest.in

3) in the setup.py, i had these lines near the top:

if sys.version_info[0] == 2:
    base_dir = 'python2'
elif sys.version_info[0] == 3:
    base_dir = 'python3'

4) in the call to setup, i specified the packages as normal:

setup(
    ...
    packages=[ 'cobs', 'cobs.cobs', 'cobs.cobsr', ],

5) i specified the base directory for the python code using a package_dir option (refer to step 3 for base_dir):

    package_dir={
        'cobs' : base_dir + '/cobs',
    },

6) for the c extensions, i gave the path:

    ext_modules=[
        extension('cobs.cobs._cobs_ext', [ base_dir + '/src/_cobs_ext.c', ]),
        extension('cobs.cobsr._cobsr_ext', [ base_dir + '/src/_cobsr_ext.c', ]),
    ],

that was about it for setup.py. the setup.py file is parsable by both python 2.x and 3.x.

7) finally, if you build a source distribution using:

python2 setup.py sdist

then it will by default pull in only the files that are specifically needed to build for that python. e.g. in the above case, you would only get the files under python2 in the source distribution, but not those under python3. but for a complete source distribution, you want to include the files for both 2.x and 3.x. to do that, create a manifest.in file that contains something like this:

include *.txt
recursive-include python2 *
recursive-include python3 *

to see what i did, see the cobs source code on pypi or bitbucket.

By salamon on September 28 2022

Answers related to “how to organize python modules for pypi to support 2.x and 3.x”

Only authorized users can answer the Search term. Please sign in first, or register a free account.