Is there a standard way to declare older versions of python unsupported?

I want to officially abandon python 2 support for a program that I support, and make full use of the capabilities of python 3. Instead of having a program that runs more or less under python 2, but does not cope with strange behavior in corner cases , I would like to officially break my python 2 program with an explicit error message "please use python 3 instead." What is the most reasonable error-prone method for unsupported python versions?

For example, I would like to import code in python 2 (at least a top-level package) to cause an error, and for distutils setup.py script, an error when trying to install or create it for python 2 (even when called through python 3, e.g. python3 setup.py sdist_dsc --with-python2 ). I would also like to include any relevant metadata to officially announce which versions of python I support. There's a Requires-Python field in PEP 345 , but I don't think it matters if I don't use distutils2.

+5
source share
3 answers

To prevent import, put this at the top of the module:

 import sys if sys.version_info[0] < 3: raise ImportError('Python < 3 is unsupported.') 

To prevent installation, put this at the top of setup.py :

 import sys if sys.version_info[0] < 3: sys.exit('Python < 3 is unsupported.') 

This will also fail before validation if you use syntax that is incompatible with Python 2 since the module will be parsed before running. Finding this out may be redundant to support "non-Python 2 support".

But I actually did not see this in practice. Most attendants simply say that it is supported and does not interfere with the verification.

+5
source

The standard way is to set classifiers in setup.py :

 if sys.version_info < (3, 3): sys.exit("error: this script requires Python 3.3 or greater.") setup(..., classifiers=[ 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', # ... other non-version info ], ...) 

For example, tulip project ( asyncio ) only supports Python 3.3 .

You can also add __init__.py to your package:

 if sys.version_info < (3, 3): raise ImportError("Python 3.3 or greater is required") 
+3
source

I would go with @ davidsm's answer, but instead I would just throw an exception:

 import sys if sys.version_info[0] < 3: raise ImportError('Only Python 3 is supported.') 
+2
source

Source: https://habr.com/ru/post/1204969/


All Articles