Newsletter
TechAnV Blog
Get updates on security engineering, Rust, eBPF, and DevSecOps. No spam, unsubscribe anytime.
Check your inbox and click the confirmation link to complete your subscription.
Programmatically comparing Python version strings#
I found myself wanting to compare the version numbers 0.63.1, 1.0 and the 1.0a13 in Python code, in order to mark a pytest test as skipped if the installed version of Datasette was pre-1.0.
This is very slightly tricky, because 1.0 is a higher version than 1.0a13 but comparing it based on string comparison or a tuple of components split by . would give the wrong result.
It turns out the packaging.version Python package solves this exact problem:
1python -m pip install packagingThen:
1from packaging.version import parse2
3v_1_0 = parse("1.0")4v_1_0a13 = parse("1.0a13")5v_0631 = parse("0.63.1")And some comparisons:
1>>> v_1_0 > v_1_0a132True3>>> v_1_0 < v_1_0a134False5>>> v_0631 < v_1_06True7>>> v_0631 < v_1_0a138TrueUsing this with pytest#
Here’s how I used this to decorate a pytest test so it would only run on versions of Datasette more recent than 1.0a13:
1from datasette import version2from packaging.version import parse3import pytest4
5
6@pytest.mark.asyncio7@pytest.mark.skipif(8 parse(version.__version__) < parse("1.0a13"),9 reason="uses row_actions() plugin hook",10)11async def test_row_actions():12 # ...Full example test here.