packaging库包含用于working with versions和其他打包相关功能的实用程序。这实现了PEP 0440 -- Version Identification,并且还能够解析不遵循PEP的版本。pip和其他常用的Python工具使用它来提供版本解析和比较。$ pip install packagingfrom packaging.version import parse as parse_version
version = parse_version('1.0.3.dev')
这与setuptools和pkg_资源中的原始代码分离,以提供更轻量级和更快的包。
在打包库存在之前,此功能在由setuptools提供的包pkg_resources中找到(并且仍然可以找到)。然而,这不再是首选,因为不再保证安装setuptools(存在其他打包工具),而且pkg_资源在导入时讽刺地使用了相当多的资源。然而,所有的文件和讨论仍然是相关的。Parsed a project's version string as defined by PEP 440. The returned value will be an object that represents the version. These objects may be compared to each other and sorted. The sorting algorithm is as defined by PEP 440 with the addition that any version which is not a valid PEP 440 version will be considered less than any valid PEP 440 version and the invalid versions will continue sorting using the original algorithm.
参考的“原始算法”是在PEP 440存在之前的旧版本文档中定义的。Semantically, the format is a rough cross between distutils' StrictVersion and LooseVersion classes; if you give it versions that would work with StrictVersion, then they will compare the same way. Otherwise, comparisons are more like a "smarter" form of LooseVersion. It is possible to create pathological version coding schemes that will fool this parser, but they should be very rare in practice.If you want to be certain that your chosen numbering scheme works the
way you think it will, you can use the pkg_resources.parse_version()
function to compare different version numbers:>>> from pkg_resources import parse_version
>>> parse_version('1.9.a.dev') == parse_version('1.9a0dev')
True
>>> parse_version('2.1-rc2') < parse_version('2.1')
True
>>> parse_version('0.6a9dev-r41475') < parse_version('0.6a9')
True