If you have ever wondered why pip install leaves a .dist-info directory behind instead of just dropping files into site-packages, or why a console script becomes a real .exe on Windows but a #!-prefixed text file on Linux, the answer lives in distlib. It is the low-level packaging library that pip once vendored and that virtualenv used as its engine. It is deliberately small, carries no third-party runtime dependency, and sits underneath the friendlier tools you actually type at the shell.
The codebase is modest but broad: thirteen Python modules and roughly 10,700 lines, with __version__ = '0.4.5.dev0' in distlib/__init__.py (line 10). Inside those files are PEP 376 installed-distribution discovery, PEP 440 version comparison, PEP 425/427 wheel handling, PEP 508 environment markers, PEP 566/643 metadata, and the entry-point machinery that turns foo = bar:main into a runnable command. None of it is magic; all of it is inspectable, which is exactly the point of a low-level toolbox.
This tour deliberately avoids re-listing the README feature matrix. Instead it follows three concrete journeys through the source — a path string from sys.path becoming a Distribution, a PKG-INFO header block becoming a normalised Metadata object, and an entry point becoming a launcher — and points at the functions and line numbers that do the work. If you maintain packaging tooling, or want to understand why pip behaves as it does, these three seams are worth knowing.
Distlib's twelve key modules and the real imports that connect them, grouped into metadata, resolution, index, install, scripts, and support.
Reading the overview from left to right: metadata and the installed database form the left column; locating and resolution sit in the middle; the wheel builder, script maker, index client, and support utilities fan out to the right. Every arrow follows an actual from . import statement in the tree, so the picture doubles as an import map.
- DistributionPath, L71 — defaults its search path to sys.path and owns the dist and egg caches.
- Metadata, L604 — reads pydist.json or falls back to a legacy header parser, then validates.
- Locator.locate, L346 — parses a requirement, filters versions, sorts by scheme key, returns the newest.
- DependencyFinder, L1090 — walks requirements recursively and tries to swap conflicting providers.
- PackageIndex, L29 — the PyPI-compatible upload, download, and signing client.
- Wheel, L179 — parses wheel filenames into name, version, pyver, abi, and arch.
- ScriptMaker, L93 — turns entry-point specifications into executables and copies plain scripts.
- get_scheme, L770 — returns the normalized, legacy, or semantic version scheme.
The detail view below zooms from modules to the classes and functions that carry the behaviour. It is intentionally denser: thirty-two nodes across eight groups, with dashed edges marking subclass relationships and solid edges marking calls or data flow.
Class- and function-level detail, showing how DistributionPath, the Locator hierarchy, Wheel, ScriptMaker, and the version schemes depend on one another.
Reading the detail, the database block is the anchor. DistributionPath yields InstalledDistribution and EggInfoDistribution objects; both subclass Distribution, which wraps a Metadata. The locator hierarchy is a classic template-method family: Locator defines locate, and PyPIJSONLocator, SimpleScrapingLocator, DirectoryLocator, and AggregatingLocator each implement _get_project. On the install side, Wheel.install calls into ScriptMaker, which is why script generation and wheel installation are never far apart in the dependency order. get_scheme feeds version comparators to both locating and metadata validation.
What distlib actually does
Distlib is not trying to be pip. It is a set of primitives: discover what is installed, read and write distribution metadata, compare versions, locate releases on an index or a directory, build and unpack wheels, and write launch scripts. Each module is focused, and the coupling is mostly one-directional toward compat and util.
The largest modules are util.py (2,075 lines), locators.py (1,320), database.py (1,328), wheel.py (1,131), compat.py (1,139), and metadata.py (1,079). markers.py is tiny at 172 lines, but it is the recursive-descent marker evaluator that decides whether a Requires-Dist line applies to your interpreter. resources.py (388 lines) is what lets the same code read package data from a directory or from a zip archive without caring which.
Little of this is new: it is stable, self-contained, and boring in the good way. When pip needed an escape hatch from setuptools internals, or virtualenv needed version-aware wheel selection, distlib could be dropped in without dragging a dependency graph along.
From source strings to runnable artefacts: three build facts
The rest of this tour is concrete. Here is how the three most important journeys actually work in the current tree.
A sys.path entry becomes a Distribution
DistributionPath.__init__ (database.py, line 76) begins with if path is None: path = sys.path, so by default every entry on your interpreter’s search path is fair game. It then initialises two caches — one for dist-info distributions and one for legacy egg distributions — and selects the default version scheme for comparisons.
The work happens in _yield_distributions (line 111). For each path entry it asks resources.finder_for_path(path) (line 120) for a finder, skips anything that is not a container, and then sorts the container’s resources (line 126). It keeps a seen set (line 118) so that symlinked aliases of the same directory are not reported twice — a real problem on Debian and Ubuntu layouts where several paths resolve to identical inodes. A .dist-info suffix (line 132) triggers a metadata probe that tries pydist.json, then metadata.json, then METADATA (line 133) before constructing an InstalledDistribution. Egg directories take the older path and produce an EggInfoDistribution. get_distribution (line 220) later lowercases the requested name and answers straight from the name index in the cache.
The significance is that discovery is metadata-first, not filename-first. distlib does not guess from foo-1.2.dist-info; it opens the metadata and lets the Name and Version fields speak.
A PKG-INFO block becomes normalised Metadata
Metadata (metadata.py, line 604) accepts a path, a file object, or a mapping, and the constructor (line 649) decides which world it is in. If you hand it bytes, it decodes UTF-8 and first tries json.loads (line 680), validating the result as distlib’s own JSON metadata with metadata_version 2.0. If JSON parsing raises ValueError, it falls back to LegacyMetadata (line 689), which reads the familiar RFC-822 header block from PKG-INFO or METADATA.
Validation is strict in exactly one direction: _validate_mapping (line 914) rejects any mapping whose metadata_version is not '2.0' (line 915), then checks mandatory keys per scheme. The bridge between the two worlds is the mapped_keys table (line 697). One entry is 'extras': ('Provides-Extra', list) (line 703), so a JSON extras list maps cleanly onto the core-metadata Provides-Extra field. When distlib writes legacy headers it rounds back the other way and emits Provides-Extra sorted (line 1029).
Version detection is table-driven. _version2fieldlist (line 111) maps a metadata version to its legal field tuple, covering 1.0 through 2.5, and _best_version infers the highest legal version from the fields actually present. That is why a half-modernised PKG-INFO still loads instead of crashing.
An entry point becomes a launcher
ScriptMaker (scripts.py, line 93) is the part most people meet without noticing. Its make method (line 429) calls get_export_entry on the specification. If the result is None, it treats the string as a filename and copies it via _copy_script; otherwise it calls _make_script to generate a stub. The generated stub is the small if __name__ == '__main__': shim that imports your module and calls your function.
The platform branch lives in _write_script (line 263). On POSIX the script is written as text with a shebang and set_executable_mode (line 321) sets the executable bit. On Windows, use_launcher is true when add_launchers is set and the platform is NT (line 264): the method fetches a launcher from _get_launcher (line 414), builds an in-memory ZIP whose only member is __main__.py, and then concatenates launcher + shebang + zip_data (line 282). The final name gets a .exe suffix (line 291). _get_launcher chooses t64.exe for console or w64.exe for GUI by testing struct.calcsize('P') and appending -arm on win-arm64, then returns prefetched bytes from the WRAPPERS table loaded at import time.
The shebang itself is not naive. _build_shebang (line 149) uses a plain #! line only when the executable has no spaces and the whole line fits under 127 bytes on Linux or 512 on macOS. Otherwise it writes a /bin/sh trampoline that works whether the file is executed by the shell or by Python. The prebuilt launcher is the native PC/launcher.c stub, whose find_shebang (line 212) and find_executable_and_args (line 868) locate the interpreter and pass the appended zip to it.
How the modules fit together
locators.py is where the pieces meet. Locator (line 86) is abstract; locate (line 346) parses the requirement, keeps only matching versions, filters prereleases unless asked, sorts by the scheme key, and returns the newest. PyPIJSONLocator uses the JSON API, SimpleScrapingLocator crawls the simple index with a worker thread pool, DirectoryLocator scans a local folder, and AggregatingLocator merges child results. DependencyFinder (line 1090) layers recursive resolution on top.
index.py is the upload side: PackageIndex handles multipart form encoding, GnuPG signing, and digest-checked downloads, but it is deliberately separate from locating. wheel.py builds and installs PEP 427 archives, and compatible_tags (line 1012) generates the interpreter’s tag priority list. version.py exposes one VersionScheme per policy; get_scheme (line 770) returns normalized by default, with legacy and semantic available. markers.py turns a PEP 508 string into a parsed tree and evaluates it.
You can see the lineage in wheel-specific tooling: the separate wheel project grew out of the same code that lives here in distlib/wheel.py. If you want the higher-level view of that format, the wheel source tour is a good companion, because distlib implements the low-level half while the wheel project implements the command-line half.
Why pip and virtualenv still matter here
Two projects keep distlib relevant. pip vendored distlib for years, which is why pip’s script generation, metadata handling, and version comparison share distlib’s exact quirks — the Provides-Extra casing, the 127-byte shebang limit, the t64.exe stub. If you have debugged a pip script that refuses to launch, you have probably been reading distlib behaviour through pip’s wrapper. The pip source tour fills in how pip wires those calls into its resolver and installer.
virtualenv leaned on distlib as its engine for interpreter handling, script writing, and version checks before it grew its own abstractions. That shared ancestry explains why virtualenv and pip agree on so many edge cases. The virtualenv source tour shows how the higher-level environment builder consumes the same primitives this library exposes.
Honest Limits
distlib is mature, not trendy. It still advertises Python 2.7 support in setup.cfg (requires_python >= 2.7), and compat.py contains a large sys.version_info[0] < 3 branch marked # pragma: no cover. Some modules are effectively frozen: legacy version handling and egg-info support exist for historical reasons and are not where new work happens.
The JSON metadata format (pydist.json, metadata_version 2.0) is a distlib dialect, not a PEP you will find in core-metadata; the package round-trips it and can emit legacy headers, but it is not what modern build backends produce. The PackageIndex upload path is legacy PyPI API territory. And the Windows launcher is confirmed by C code and prebuilt binaries rather than by a cross-platform test run in this tour.
Read distlib as a reference implementation: exact, conservative, and willing to carry old behaviour forward so the tools above it do not break. It is a narrow brief, executed very well. Enjoyed this post? Never miss out on future posts by following us