如果 Python 版本可能包含超过 3 个字符,PEP 508 中环境标记变量 `python_version` 的定义是什么?

What's with the definition of Environment Marker Variable `python_version` in PEP 508 if the Python version might consist of more than 3 characters?

我偶然发现了一个简单的问题。这不是很重要,但我对其中的原因很感兴趣,但还没有找到快速的答案。

根据PEP 508 -- Environment Markers (section "Specification" - "Environment markers")标记变量python_version定义为platform.python_version()[:3]

所以对于 Python 3.5.2,python_version 将是 3.5

但是,如果主要或次要版本号高于 9 怎么办?版本号将包含超过 3 个字符,[:3] 会裁剪它。这不是未来 Python 版本的可能性吗?

为什么不使用像 ".".join(platform.python_version().split(".", 2)[:2]) 这样的东西,它看起来仍然很基本并且不会使代码过于复杂?

作为此问题的后续内容,此问题现已更正。请参阅更新后的 PEP 中的 issue #560, pull request #1123 and the summary of changes

  • The definition of python_version was changed from platform.python_version()[:3] to '.'.join(platform.python_version_tuple()[:2], to accommodate potential future versions of Python with 2-digit major and minor versions (e.g. 3.10). [7]

packaging库源代码has followed suit.


原回答

我确定这只是出于文档目的的疏忽或简化。 意图显然是提供一个major.minor版本字符串。

请注意,从历史上看,从未有过两位数的次要版本号。到目前为止,Python 一直只用一位数。到目前为止,最高的数字是 1.62.73.7。这并不是说将来永远不会有 3.10,但到目前为止,它还没有出现。

我想象一个实际的实现使用 platform.python_version_tuple():

return '.'.join(platform.python_version_tuple()[:2]

major, minor, patch = platform.python_version_tuple()
return '{}.{}'.format(major, minor)

然而,这两种形式都比较冗长,以适应旨在记录而不是规定代码的 PEP table 专栏。

如有疑问,请写信给 Python-dev 邮件列表。我敢肯定,如果这变得如此混乱以至于出现问题,可以调整 PEP。

至于点子;它使用销售 packaging library to handle environment markers, which has implemented the python_version marker verbatim as specced in the PEP。如果你对此有强烈的感觉,你可以在那里提出一个问题,PEP 维护者在那个项目上很活跃。

请注意,还有 充足的 时间。到目前为止,3.x 个版本每个版本都需要大约 18 个月的时间才能出现(3.2:2011-02、3.3:2012-09、3.4:2014-03、3.5:2015-09、3.6:2016-12、3.7:预期2018-06),所以我们有 5 年左右的时间来解决这个问题。