I have a python library that has a dependency on importlib. importlib is in the standard library in Python 2.7, but is a third-party package for older pythons. I typically keep my dependencies in a pip-style requirements.txt. Of course, if I put importlib in here, it will fail if installed on 2.7. How can I conditionally install importlib only if it's not available in the standard lib?

share|improve this question
up vote 10 down vote accepted

I don't think this is possible with pip and a single requirements file. I can think of two options I'd choose from:

Multiple requirements files

Create a base.txt file that contains most of your packages:

# base.txt
somelib1
somelib2

And create a requirements file for python 2.6:

# py26.txt
-r base.txt
importlib

and one for 2.7:

# py27.txt
-r base.txt

Requirements in setup.py

If your library has a setup.py file, you can check the version of python, or just check if the library already exists, like this:

# setup.py
from setuptools import setup
install_requires = ['somelib1', 'somelib2']

try:
    import importlib
except ImportError:
    install_requires.append('importlib')

setup(
    ...
    install_requires=install_requires,
    ...
)
share|improve this answer
1  
I ended up using multiple requirements files. Thanks. – David Eyk Mar 28 '12 at 17:15
    
Question... How does this interact with pip? Does pip just iterate over the items in "install_requires"? If so, can you just include the version of the lib in the list? For example ['somelib1==1.02',] – David S Aug 22 '12 at 22:19
    
@DavidS yes, you can put the version dependency in install_requires – jterrace Aug 22 '12 at 22:24

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.