How do I mark a Python package as Python 2 only?

Question:

I have a Python package that only runs on Python 2. It has the following classifiers in its setup.py:

setup(
    # ...
    classifiers=[
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2 :: Only',
    ])

However, if I create a virtualenv with Python 3, pip happily installs this package.

How do I prevent the package being installed? Should my setup.py throw an error based on sys.version_info? Can I stop pip even downloading the package?

Asked By: Wilfred Hughes

||

Answers:

In setup.py, add this:

import sys
if sys.version_info[0] != 2:
    sys.stderr.write("This package only supports Python 2.n")
    sys.exit(1)
Answered By: Lennart Regebro

In newer versions of setuptools and pip, if you’re using setup.py, here’s how to specify a requirement of Python 2 only (specifically Python 2.7):

from setuptools import setup

setup(
    name="my_package_name",
    python_requires='>=2.7,<3.0',
    # ...
)

It would also be good to include classifiers, like this:

setup(
    name="my_package_name",
    python_requires='>=2.7,<3.0',
    classifiers=[
        "Programming Language :: Python :: 2.7",
        "Programming Language :: Python :: 2 :: Only",
    ],
)
Answered By: Flimm
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.