我应该在何时何地检查Python的最低版本? [英] When/where should I check for the minimum Python version?
问题描述
这个问题告诉我如何检查Python版本.对于我的程序包,我至少需要Python 3.3:
This question tells me how to check the version of Python. For my package I require at least Python 3.3:
MIN_VERSION_INFO = 3, 3
import sys
if not sys.version_info >= MIN_VERSION_INFO:
exit("Python {}.{}+ is required.".format(*MIN_VERSION_INFO))
但是应该在哪里/何时进行此检查?
我想为通过pip
(sdist和wheel)或python setup.py install
安装的用户生成最清晰的错误消息.像这样:
I want to produce the clearest possible error message for users installing via pip
(sdist and wheel) or python setup.py install
. Something like:
$ pip -V
pip x.x.x from ... (Python 3.2)
$ pip install MyPackage
Python 3.3+ is required.
$ python -V
Python 3.2
$ python setup.py install
Python 3.3+ is required.
推荐答案
兼容性检查的主要目的是让此检查优雅地处理兼容性问题或在不兼容引起问题之前优雅地退出并给出解释.
The primary point of a compatibility check is to have this check either elegantly handle a compatibility issue or gracefully exit with an explanation before the incompatibility causes problems.
我会将其放在setup.py
的顶部附近,否则它将被称为属于您的第一个脚本.最佳实践是不要在__init__.py
中包含代码(除非您要制作MAJOR软件包,否则,我认为),但是如果您那里已经有很多代码,那就很好了.
I'd put it near the top of setup.py
, or the first script that belongs to you that will be called. Best practice is not to include code in __init__.py
(unless you're making a MAJOR package, I'd opine), but if you already have a lot of code there, it's fine.
我可以找到最快的参考点:旧的 Python 2.6 unittest
模块在其文档字符串,导入和__all__
之后很自然地在顶部处进行了测试.
The quickest point of reference I can find: The old Python 2.6 unittest
module had a test for it near the top, naturally, after the module docstring, imports, and __all__
.
另一参考点显示了__init__.py
还是在顶部附近,尽管此处紧接在文档字符串和sys
的导入之后,这是检查所必需的.在同一套库中的__init__.py
中,还有其他类似的用法示例.
Another point of reference shows a compatibility check in an __init__.py
, again, near the top, though here it is immediately after the docstring and an import of sys
, required for the check. There are other similar examples of this usage in __init__.py
in this same set of libraries.
这篇关于我应该在何时何地检查Python的最低版本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!