Ben Chuanlong Du's Blog

It is never too late to learn.

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!

Version Handling

In [1]:
from packaging.version import Version, parse
In [2]:
v1 = parse("1.0a5")
v1
Out[2]:
<Version('1.0a5')>
In [3]:
v2 = Version("1.0")
Out[3]:
<Version('1.0')>
In [4]:
v1 < v2
Out[4]:
True
In [5]:
v1.epoch
Out[5]:
0
In [6]:
v1.release
Out[6]:
(1, 0)
In [7]:
v1.pre
Out[7]:
('a', 5)
In [8]:
v1.is_prerelease
Out[8]:
True
In [9]:
v2.is_prerelease
Out[9]:
False
In [10]:
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'
In [12]:
Version("1.0").post
In [13]:
Version("1.0").is_postrelease
Out[13]:
False
In [14]:
Version("1.0.post0").post
Out[14]:
0
In [15]:
Version("1.0.post0").is_postrelease
Out[15]:
True
In [1]:
from packaging.specifiers import SpecifierSet
from packaging.version import Version
In [3]:
spec = SpecifierSet("")
spec
Out[3]:
<SpecifierSet('')>
In [4]:
"1.0" in spec
Out[4]:
True
In [17]:
SpecifierSet("==1.0")
Out[17]:
<SpecifierSet('==1.0')>
In [2]:
spec1 = SpecifierSet("~=1.0")
spec1
Out[2]:
<SpecifierSet('~=1.0')>
In [3]:
spec2 = SpecifierSet(">=1.0")
spec2
Out[3]:
<SpecifierSet('>=1.0')>
In [13]:
spec3 = SpecifierSet("~=1.0,>=1.0")
spec3
Out[13]:
<SpecifierSet('>=1.0,~=1.0')>

Combine specifiers.

In [14]:
combined_spec = spec1 & spec2
combined_spec
Out[14]:
<SpecifierSet('>=1.0,~=1.0')>

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

In [15]:
combined_spec == spec3
Out[15]:
True

Implicitly combine a string specifier.

In [5]:
combined_spec &= "!=1.1"
combined_spec
Out[5]:
<SpecifierSet('!=1.1,>=1.0,~=1.0')>

Create a few versions to check for contains.

In [7]:
v1 = Version("1.0a5")
v1
Out[7]:
<Version('1.0a5')>
In [8]:
v2 = Version("1.0")
v2
Out[8]:
<Version('1.0')>

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

In [9]:
v1 in combined_spec
Out[9]:
False
In [10]:
v2 in combined_spec
Out[10]:
True

You can doo the same with a string based version.

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

References

packaging

In [ ]:
 

Comments