There is a python code, which is supposed to support Python 3, but may or may not run in Python 2.7. For example, this snippet can run in both Python 2.7 and Python 3. What is the standard way to enforce and recommend Python 3 compatibility in strict mode, even if the code runs fine on Python 2.7 ?
print('This file works in both')
print('How to throw an exception,and suggest recommendation of python 3 only ?')
Python 2.7 : https://ideone.com/bGnbvd
Python 3.5 : https://ideone.com/yrTi3p
There can be multiple hacks and exceptions, which work in Python 3, and not in Python 2.7, which can be used to achieve this. I am looking for most recommended way of doing this in the beginning of files/modules/projects.
If it is a proper Python package with the setup.py
, you can use several things:
python_requires
classifier
If your project only runs on certain Python versions, setting the
python_requires
argument to the appropriate PEP 440 version specifier string will prevent pip from installing the project on other Python versions.
Sample: python_requires='>=3',
Since the support for python_requires
classifier has been added relatively recently, you should account for users installing your package with older versions of pip
and setuptools
. In this case you can check the sys.version_info
inside the setup.py
file like Django does:
import sys
CURRENT_PYTHON = sys.version_info[:2]
REQUIRED_PYTHON = (3, 5)
# This check and everything above must remain compatible with Python 2.7.
if CURRENT_PYTHON < REQUIRED_PYTHON:
sys.stderr.write("""...""")
sys.exit(1)
Programming Language
Python version classifiers:
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3 :: Only',
And, as a bonus, if the package is distributed through PyPI package index, python_requires
and other classifiers are going to be displayed on the package home page.
You could simply check the sys.version_info
:
import sys
if sys.version_info[0] < 3:
raise SystemExit("Use Python 3 (or higher) only")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With