Interpret Version Specifiers with PEP 440
Core idea
Version requirements use PEP 440 syntax. A range such as >=1.4,<2 requires both comparisons. ~=1.4.5 permits compatible releases starting at 1.4.5 and below 1.5. Use the external packaging library rather than comparing version strings lexicographically. Pre-release selection and dependency resolution require additional rules.
from packaging.version import Versionprint(Version('1.10') > Version('1.9'))print(Version('1.0') == Version('1.0.0'))The library interprets numeric release segments and equivalent trailing zeros.
Expected output:
TrueTrueTest a compatible range
from packaging.specifiers import SpecifierSetallowed = SpecifierSet('~=1.4.5')for version in ['1.4.5', '1.4.9', '1.5.0']: print(version, version in allowed)The final release segment may increase without crossing 1.5.
Expected output:
1.4.5 True1.4.9 True1.5.0 FalseCommon mistake
Do not substitute string comparison for version semantics or assume a range is a lock. These snippets require the third-party packaging library in the selected environment.
Practice
Compare >=1.4,<2 and ~=1.4.5 for 1.4.4, 1.4.8 and 1.9.0. Explain why the two sets differ.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Version specifiers
Check your understanding of version specifiers.
What is printed?
from packaging.version import Versionprint(Version("2.0rc1") < Version("2.0"))What is printed?
from packaging.specifiers import SpecifierSetprint("2.0" in SpecifierSet(">=1,<2"))What does the comma between specifiers mean?
Which upper boundary does ~=1.4.5 exclude?