Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Hands on the Python Module Packaging

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

** Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement! **

Version Handling

from packaging.version import Version, parse
v1 = parse("1.0a5")
v1
<Version('1.0a5')>
v2 = Version("1.0")
<Version('1.0')>
v1 < v2
True
v1.epoch
0
v1.release
(1, 0)
v1.pre
('a', 5)
v1.is_prerelease
True
v2.is_prerelease
False
Version("french toast")
---------------------------------------------------------------------------
InvalidVersion                            Traceback (most recent call last)
<ipython-input-10-6e617289b19c> in <module>
----> 1 Version("french toast")

/usr/local/lib/python3.8/site-packages/packaging/version.py in __init__(self, version)
    275         match = self._regex.search(version)
    276         if not match:
--> 277             raise InvalidVersion("Invalid version: '{0}'".format(version))
    278 
    279         # Store the parsed out pieces of the version

InvalidVersion: Invalid version: 'french toast'
Version("1.0").post
Version("1.0").is_postrelease
False
Version("1.0.post0").post
0
Version("1.0.post0").is_postrelease
True
from packaging.specifiers import SpecifierSet
from packaging.version import Version
spec = SpecifierSet("")
spec
<SpecifierSet('')>
"1.0" in spec
True
SpecifierSet("==1.0")
<SpecifierSet('==1.0')>
spec1 = SpecifierSet("~=1.0")
spec1
<SpecifierSet('~=1.0')>
spec2 = SpecifierSet(">=1.0")
spec2
<SpecifierSet('>=1.0')>
spec3 = SpecifierSet("~=1.0,>=1.0")
spec3
<SpecifierSet('>=1.0,~=1.0')>

Combine specifiers.

combined_spec = spec1 & spec2
combined_spec
<SpecifierSet('>=1.0,~=1.0')>

The combination of spec1 (~=1.0) and spec2 (>=1.0) is the same as spec3 (~=1.0,>=1.0).

combined_spec == spec3
True

Implicitly combine a string specifier.

combined_spec &= "!=1.1"
combined_spec
<SpecifierSet('!=1.1,>=1.0,~=1.0')>

Create a few versions to check for contains.

v1 = Version("1.0a5")
v1
<Version('1.0a5')>
v2 = Version("1.0")
v2
<Version('1.0')>

Check a version object to see if it falls within a specifier.

v1 in combined_spec
False
v2 in combined_spec
True

You can doo the same with a string based version.

"1.4" in combined_spec
True
Filter a list of versions to get only those which are contained within a specifier.
vers = [v1, v2, "1.4"]
list(combined_spec.filter(vers))
[<Version('1.0')>, '1.4']

References

packaging