Every pip install makes small decisions most developers never see. Is 1.0.0 the same version as 1? Does >=2,<1 mean anything? Should this interpreter accept cp312-abi3-manylinux_2_28_x86_64, or only the pure-Python fallback? These look like trivia until a resolver picks a different wheel than you expected, or a private index serves a filename one tool accepts and another rejects.
The library that answers them for almost the entire Python ecosystem is pypa/packaging. It is deliberately small and dependency-free, yet it implements the parts of PEP 440, PEP 508 and PEP 425 that other tools need to agree on. pip consumes it while turning requirement strings into install plans; build backends such as poetry and hatch rely on the same normalization rules when writing metadata. When two tools disagree about a version or a tag, the bug is often here.
This tour follows the current main tree at 26.5.dev0, with the latest release 26.4 published on 2026-11-23. The interesting part is the machinery underneath: named-group regex segments, a comparison key built from flat integer tuples, interval algebra in place of per-operator checks, a shared tokenizer and recursive-descent parser, and tag preference derived from the running interpreter.
The public surface groups into four layers: specification objects, the parsing layer shared by requirements and markers, tag selection, and artifact helpers.
Reading the overview from left to right:
- Version, L355 is the slotted representation of one PEP 440 version, holding epoch, release, pre, post, dev and local as separate fields.
- VERSION_PATTERN, L247 is the public regex, assembled from a named-group pattern and adapted for the running interpreter.
- _cmpkey, L1194 turns those fields into a flat tuple so ordinary Python comparisons produce PEP 440 ordering.
- Specifier, L236 holds one operator and version, validated by a large verbose regex before any comparison happens.
- SpecifierSet.to_range, L1247 exposes the interval view that the newer range code builds from a comma-separated set.
- Requirement, L79 is a parsed PEP 508 string with name, extras, specifier, URL and marker fields.
- Marker, L523 stores the parsed environment expression instead of re-parsing it on every evaluation.
- sys_tags, L992 yields every tag the current interpreter supports, best match first.
- canonicalize_name, L84 shows the project’s preference for explicit string work over regular expressions in hot paths.
The detailed view: version segments feed both direct comparison keys and interval bounds, while requirements and markers share one tokenizer and parser.
A regex with named segments, plus a shortcut
The center of version.py is a single verbose pattern at line 187. It is deliberately not anchored, because third-party code embeds it inside larger filename patterns. It names each piece the class needs: epoch, release, pre with pre_l and pre_n, post with two numeric alternatives, dev, and local. It also accepts the separators people type, so 1.0-alpha, 1.0_alpha and 1.0alpha land in the same group.
The pattern uses possessive quantifiers such as ?+ and ++. Those are fast, but they arrived in Python 3.11 with early bugs. _adapt_possessive at line 225 rewrites the pattern at import time based on interpreter name and version, and the public VERSION_PATTERN at line 247 is the adapted result.
Version.__init__ at line 423 does not always run the regex. It first checks whether every character belongs to _SIMPLE_VERSION_INDICATORS, a frozenset at line 275. A string like 1.2.3 is split on dots and mapped to integers directly, much cheaper than a regex match. Only versions with a prefix, suffix or local segment fall through to self._regex.fullmatch at line 462. Results live in eight slots at line 392, including _key_cache and _hash_cache, so repeated comparisons rebuild nothing.
Two helpers normalize the pieces. _parse_letter_version at line 1141 lowercases the letter, maps synonyms through a table, and supplies an implicit zero when no number follows. _parse_local_version at line 1168 splits on dots, underscores and hyphens, converting digit runs to integers and leaving the rest lowercase.
Ordering without a segment object
PEP 440 ordering is full of edge cases: pre-releases sort before the final release, post-releases after it, dev releases before pre-releases, and local versions have their own rules. The current code encodes all of it in a plain tuple.
_cmpkey at line 1194 receives the six fields and returns (epoch, release, suffix) or a four-item tuple when a local segment exists. The suffix is a flat six-integer tuple (pre_rank, pre_n, post_rank, post_n, dev_rank, dev_n). _PRE_RANK maps a, b and rc to 0, 1 and 2 at line 1182; a dev-only release gets -1, a stable release gets 3, and _STABLE_SUFFIX at line 1191 precomputes the common case. Post and dev ranks are expressed as 0 or 1, which is enough because their numbers only matter after the rank differs.
Trailing zeros are stripped before the key is built. The loop at lines 1238 to 1241 removes them, which is why 1.0.0 and 1 compare equal. Local segments become (segment, "") for integers and (-1, segment) for strings, so strings sort before integers and the shorter local version wins when one is a prefix. Because the result is a tuple of tuples, _BaseVersion at line 131 implements all six rich comparisons by comparing _key values.
From operator dispatch to interval algebra
This is the biggest architectural change in the tree. Older releases answered every membership question with a branch per operator inside Specifier.contains. The current code keeps a fast path: _fast_match at line 86 compares cached comparison keys directly for >=, <=, ==, !=, < and >, but only when the parsed version has no local segment and the specifier is not ~=, === or a wildcard. The comment at lines 118 to 135 spells out the cases it refuses to handle, such as <V behaving like <V.dev0.
Everything else goes through intervals. Specifier._to_intervals at line 473 calls bounds_for_spec in _ranges.py at line 744, caching the result. SpecifierSet.__init__ at line 873 splits on commas, strips each part and builds Specifier objects; is_unsatisfiable at line 1173 checks whether the intersection is empty. The public VersionRange class at line 1098 of ranges.py, introduced as a public API in 26.3, exposes the algebra: intersection, union, complement, difference, subset and disjoint checks, membership and filtering. RangeRelation at line 71 packages the relation result into an enum.
The scale difference is striking. ranges.py is 2468 lines, while version.py is 1269, specifiers.py is 1569 and tags.py is 1082. Much of that range code translates between textual specifiers and interval bounds without changing semantics. to_specifier_set at line 2105 converts back only where a PEP 440 form exists.
The specifier parser itself remains a regex. _specifier_regex_str at line 264 builds four alternatives: identity ===, equality and inequality with wildcard and local support, the compatible operator ~=, and the ordered operators. It is compiled with verbose and ignore-case flags at line 358. Specifier.__init__ at line 387 rejects anything that does not full-match, then slices the operator by length. The regex says what syntax is legal; bounds_for_spec says what that syntax means.
One tokenizer, two grammars
Requirements and markers used to be parsed with separate regular expressions, and before 22.0 markers depended on pyparsing. The changelog records the replacement with a hand-written parser and the end of all runtime dependencies. The tree still reflects that decision: requirements.py at line 137 calls _parse_requirement at line 139, which lives in _parser.py at line 112, and markers import parse_marker from the same module at line 25.
_parser.py is a recursive-descent parser with grammar fragments written as docstrings. _parse_requirement at line 116 begins with an identifier, optional whitespace, optional extras, then requirement details; _parse_requirement_details at line 136 handles either an @ URL form or a specifier followed by an optional marker. The tokenizer in _tokenizer.py at line 97 is rule-driven and emits tokens with source positions, which is why InvalidRequirement at line 47 can carry message, source and span attributes added in 26.4.
Evaluation is separate from parsing. Marker.evaluate at line 655 delegates to _evaluate_markers at line 368, which walks marker items, starts a new group on or, ignores and, and returns any(all(item) for item in groups). Variable operands are looked up in the environment mapping, while literals are normalized before comparison. default_environment at line 453 returns a cached dictionary built by _cached_default_environment at line 428, so repeated evaluations do not re-query platform and sys. The extra key is special: it can be a set of selected extras, handled by a dedicated branch.
Tags are a generated preference list
Wheel selection looks like a set membership test, but it is really an ordering problem. A Tag at line 133 is an immutable triple of interpreter, ABI and platform, with four slots at line 151 and a hash computed once. sys_tags at line 992 chains generators rather than building a list, because callers may stop early once they find a match.
For CPython, cpython_tags at line 413 emits cp312-<abi>-<platform> for each supported ABI, then cp312-abi3-<platform>, then cp312-abi3t-<platform>, then cp312-none-<platform>, and finally older abi3 tags down the version range. The abi3t tag was added in 26.1. compatible_tags at line 621 adds the pure py3-none-<platform> family and, when an interpreter is known, <interpreter>-none-any. sys_tags chooses a generator from interpreter_name(), then appends the compatible stream. The docstring at lines 1000 to 1002 states the priority: interpreter, then platform, then ABI.
Platform tags are where system probing happens. platform_tags at line 926 dispatches on platform.system(). Linux goes to _linux_platforms, which calls _manylinux.platform_tags at line 237 and _musllinux.platform_tags at line 61. The manylinux module reads the glibc version, checks architecture compatibility, and optionally consults ELF headers through ELFFile in _elffile.py at line 42. The 26.3 changelog notes that native linux_* tags now sort before manylinux and musllinux tags, a behavioral fix that changes which wheel is preferred.
Filename helpers complete the loop. parse_wheel_filename at line 202 rejects names whose dash count is not four or five at line 264, splits name, version, build and compressed tag set, and returns a frozenset of Tag objects. parse_sdist_filename at line 308 extracts a canonical name and a Version. Both call canonicalize_name, which lowercases the name, replaces underscores and dots with hyphens, and collapses repeated hyphens; the comment at lines 119 to 125 explains that this beats re.sub and str.translate on this hot path.
Honest Limits
packaging implements specifications; it does not resolve dependencies. There is no backtracking solver, no index client and no download logic. pylock.py models a lockfile and offers wheel selection through the tag machinery, but it does not decide which versions to lock. That work belongs to pip, poetry, uv and their peers.
The version parser is still a regex with hand-written validation around it. It covers PEP 440’s grammar and normalization rules, but it is not a general parser, and its possessive-quantifier adaptation is a compatibility shim, not a guarantee across every interpreter.
Tag generation can only report what the runtime can see. On Linux, a statically linked interpreter or unusual container can hide the glibc or musl version, and fallback tags are conservative. On macOS and Windows the generators rely on platform APIs that can disagree with a cross-build environment.
Finally, this tour tracks Enjoyed this post? Never miss out on future posts by following us main at 26.5.dev0. Line numbers move with every release, and several range APIs are recent enough that older documentation will describe the previous operator-dispatch design. The diagram is a map, not a contract; the source is the authority.