Comparing Version Numbers in Python
When walking a directory that contains multiple versions of the same egg, ensuring that only the latest version is added to the sys.path can pose a challenge due to the non-intuitive ordering of version strings when comparing them as strings.
Using packaging.version
Python provides an elegant solution through the packaging.version module, which supports PEP 440-style ordering of version strings. This module offers the Version class, which can be used to compare versions accurately.
from packaging.version import Version # Example: version1 = Version("2.3.1") version2 = Version("10.1.2") print(version1 < version2) # True
Legacy Methods
An older method for comparing version strings is distutils.version. However, it's deprecated and adheres to the superseded PEP 386. It provides two classes, LooseVersion and StrictVersion.
from distutils.version import LooseVersion, StrictVersion # LooseVersion compares versions loosely: version1 = LooseVersion("2.3.1") version2 = LooseVersion("10.1.2") print(version1 < version2) # True # StrictVersion is stricter in its comparison: version1 = StrictVersion("2.3.1") version2 = StrictVersion("10.1.2") print(version1 < version2) # True # However, it doesn't recognize valid PEP 440 versions as strict: version1 = StrictVersion("1.3.a4") print(version1) # ValueError: invalid version number '1.3.a4'
Conclusion
When comparing version numbers in Python, packaging.version offers a reliable and elegant solution. It adheres to the current PEP 440 specification and provides a clean and concise API for version comparison.
The above is the detailed content of How to Reliably Compare Version Numbers in Python?. For more information, please follow other related articles on the PHP Chinese website!