Paul
Paul

Reputation: 311

What is the best way to handle dependencies based on the Python version?

If I have a setup.py using SetupTools, is there a way to specify install_requires for a specific version of Python?

E.g., if one of my modules requires the use of an OrderedDict, I would like versions of Python <2.7 to install the ordereddict1.1 package from PyPI, but there's no reason to (and probably a bad idea) to add that to a Python 2.7 installtion.

What's the best way to handle this? Separate eggs for the different versions? I know that's necessary for non-pure modules but this would be pure Python.

Upvotes: 3

Views: 355

Answers (2)

abarnert
abarnert

Reputation: 365657

Your setup.py is just plain Python code, so you do the exact same thing you do in your source code in the setup script.


The documentation shows how to switch on sys.version_info for doing 3.x vs. 2.x code, but it works the same way for 2.7 vs. 2.6. So, if your code is doing this:

if sys.version_info < (2, 7);
    from ordereddict import OrderedDict
else:
    from collections import OrderedDict

… then your setup script can do this:

import sys
from setuptools import setup

extra_install_requires = []
if sys.version_info < (2, 7):
    extra_install_requires.append('ordereddict>=1.1')

setup(
    # ...
    install_requires = [...] + extra_install_requires,
    # ...
)

On the other hand, if your code is doing this:

try:
    from collections import OrderedDict
except ImportError:
    from ordereddict import OrderedDict

… then, while you could use version_info, you might as well just do this:

extra_install_requires = []
try:
    from collections import OrderedDict
except ImportError:
    extra_install_requires.append('ordereddict>=1.1')

Either way, if you, e.g., pip-2.5 install this package, it'll download and install the ordereddict module (unless the user already has 1.1 or later); with 2.7, it won't do anthying.


If you're looking to distribute pre-built eggs, then yes, they will end up different for Python 2.6 and 2.7. For example, after python2.6 setup.py bdist_egg && python2.7 setup.py bdist_egg, you will end up with dist/Foo-0.1-py2.6.egg and dist/Foo-0.1-py2.7.egg, and you will have to distribute both of them.

Upvotes: 4

mata
mata

Reputation: 69012

You could just check for the python version and dynamically append the requirement for older python versions:

from setuptools import setup
import sys

install_requires = [
   # your global requirements
   # ...
]

if sys.version_info < (2, 7):
    install_requires.append('ordereddict >= 1.1')

setup(
    # ...
    install_requires=install_requires
    # ...
)

Upvotes: 0

Related Questions