Comparing Version Numbers in Python

The distutils module is going to be deprecated in Python 3.10, and to be removed in Python 3.12.

Hence, my current standard way of comparing version number strings is using pkg_resources module (part of setuptools):

>>> from pkg_resources import parse_version as version
>>> version("1.0")
>>> version("1.8.9") < version("2.0")
>>> version("2.0.9") < version("2.1")
>>> version("2.1-beta")
>>> version("2.1-beta") < version("2.1")
>>> version("1.markku.2")
>>> version("1.markku.1") < version("1.markku.2")

I don’t exactly know when the parse_version() function (or the pkg_resources module) was introduced in setuptools, but I’ve tested my usual Linux distros and their bundled setuptools packages (which, by default, are among the oldest that you can find…), and this worked just fine. And in many cases setuptools is upgraded anyway when creating new virtual environments.

See also: PEP 440 — Version Identification and Dependency Specification

Leave a Reply