install_requires based on python version

2019-01-31 19:05发布

问题:

I have a module that works both on python 2 and python 3. In Python<3.2 I would like to install a specific package as a dependency. For Python>=3.2.

Something like:

 install_requires=[
    "threadpool >= 1.2.7 if python_version < 3.2.0",
 ],

How can one make that?

回答1:

setuptools has support for this using environment markers.

install_requires=[
    'enum34;python_version<"3.4"',
    'pywin32 >= 1.0;platform_system=="Windows"'
]

Use of this is detailed in the official documentation. Based on the change log was added in v20.5, but the implementation wasn't stable until v20.8.1 (which was only a gap of 15 days).


Original Answer (still valid, but might be deprecated in the future):

setuptools has support for this using within the extras_require argument.

The format is the following:

extras_require={
    ':python_version=="2.7"': ["mock"],
},

It will support the other comparison operators.


Sadly, it is not mentioned in the documentation. While looking for answers, I found PEP-426 talking about "environment markers". With that phrase I was able to find a setuptools ticket with the following comment:

I've successfully used the markers feature for selectively and declaratively requiring a dependency. See backports.unittest_mock for an example. Through the 'extras', mock will be required, but only on Python 2. When I can rely on Setuptools 17.1, I can change that dependency to python_version < "3.3".



回答2:

This has been discussed here, it would appear the recommend way is to test for the Python version inside your setup.py using sys.version_info;

import sys

if sys.version_info >= (3,2):
    install_requires = ["threadpool >= 1.2.7"]
else:
    install_requires = ["threadpool >= 1.2.3"]

setup(..., install_requires=install_requires)