Every pip install ends in the same quiet moment: a .whl archive is opened, its members are copied into site-packages, a RECORD file is rewritten, and a few console scripts appear on your PATH. That last mile looks trivial until you have to reproduce it correctly for a custom deployment tool, a container base image, or an embedded interpreter. Then the details bite: scheme routing, executable bits, Windows launchers, path traversal, and hash verification.
pypa/installer exists precisely because that last mile deserves a shared, tested implementation rather than a fresh pile of zipfile.extractall calls. It is a deliberately small library — nine Python modules and roughly 1,600 lines — that turns “wheel in, files out” into a set of explicit abstractions you can reuse or replace. It is not a package manager, and it does not pretend to be one.
This tour follows the actual main tree at version 1.1.0. We will trace a wheel from the zip reader, through scheme selection and filesystem writes, into RECORD generation and entry-point scripts. Every symbol and line number below was checked against the cloned repository, including the parts where the code is more cautious than the marketing copy suggests.
The two protocols sit at the center: WheelSource reads, WheelDestination writes, and install() is the thin loop between them.
Reading the overview from left to right:
- install, L65 — the single orchestration function: scripts first, wheel members second, extra metadata third,
RECORDlast. - WheelFile, L149 — the concrete
WheelSourceover azipfile.ZipFile, deriving distribution and version from the filename. - validate_record, L231 — an opt-in integrity check that compares each archive member’s hash and size with the
RECORDrow. - SchemeDictionaryDestination, L102 — a dataclass that maps scheme names such as
purelibandscriptsto real directories. - _path_with_destdir, L138 — the safety gate:
abspathplusis_relative_torejects any member that tries to escape its scheme root. - write_to_fs, L162 — refuses silent overwrites, creates parent directories, streams bytes while hashing, then applies execute bits.
- Script.generate, L89 — builds either a POSIX script or a Windows executable by prepending a launcher binary to a zipped
__main__.py. - fix_shebang, L175 — rewrites a leading
#!pythonline to the interpreter actually running the install.
The detail view: every arrow is a real call or inheritance edge inside src/installer, from CLI parsing down to the eight bundled launcher binaries.
From .whl Bytes to Files on Disk
The entry point is small on purpose. install() first calls _process_WHEEL_file, which reads the WHEEL metadata, rejects anything whose Wheel-Version does not start with "1.", and chooses the root scheme from Root-Is-Purelib. A pure wheel lands in purelib; everything else goes to platlib. That single decision determines where the archive root is unpacked.
Next it reads entry_points.txt from the dist-info directory and, for every parsed tuple of name, module, attribute and section, calls destination.write_script. Those writes are recorded immediately as belonging to the scripts scheme. Then the member loop begins. Each archive member is converted into a RecordEntry, and the RECORD member itself is skipped because it must be regenerated at the end from the actual writes.
Path routing lives in _determine_scheme. If posixpath.commonpath([data_dir, path]) does not equal the wheel’s .data directory, the file stays in the root scheme. Otherwise the function walks the path upward with posixpath.split until it reaches the data directory, takes the next component as a scheme name, and checks it against SCHEME_NAMES, the five-value tuple ("purelib", "platlib", "headers", "scripts", "data"). An unknown .data subdirectory raises InvalidWheelSource instead of guessing.
There is one security detour that is easy to miss. Before writing a member, the loop checks whether __pycache__ appears in any parent path segment. If it does, the file is skipped with a RuntimeWarning explaining that shipping cache directories in a wheel is a security risk. It is a small policy choice embedded in the installer rather than left to each caller.
The actual filesystem write is more defensive than a plain extract. _path_with_destdir resolves both the scheme root and the target through os.path.abspath, explicitly avoiding Path.resolve for speed, and then calls is_relative_to. A member containing .. that would land outside the scheme is rejected with a ValueError. When a destdir is configured, the absolute path is re-rooted beneath that staging directory, which is what makes image-building and package-staging workflows possible.
write_to_fs then enforces overwrite_existing (default False) with a FileExistsError, creates missing parents, opens the destination in binary mode, and calls copyfileobj_with_hashing. That helper copies in 1 MiB chunks on Windows and 64 KiB elsewhere, updating the hash as it goes, and returns a URL-safe base64 digest with the padding stripped. Executable members get make_file_executable, which applies 0o777 & ~umask | 0o111 rather than blindly setting 0o777.
After the member loop, install() writes caller-supplied additional_metadata through the same destination interface, appends the RECORD row itself, and hands the accumulated entries to finalize_installation. Nothing is written outside the destination abstraction, which is what makes the core loop testable with an in-memory destination.
The Two Abstractions That Keep the Core Small
WheelSource and WheelDestination are the real API surface, and both are intentionally boring. WheelSource exposes dist_info_dir, data_dir, dist_info_filenames, read_dist_info, validate_record and get_contents. The last one must yield triples of a record tuple, a binary stream, and an executable flag. Because that contract is fully described, callers can install from a zip file, an in-memory wheel, or a custom container without touching the core loop.
WheelFile is the concrete source for ordinary .whl files. Its dist_info_dir property builds the set of top-level directories in the archive and requires exactly one .dist-info entry. It then strips the version suffix and compares the canonicalized directory name with the canonicalized distribution name, raising _WheelFileBadDistInfo when the archive claims one name in its filename and another inside. That check catches a class of malformed or malicious wheels before any bytes are written. In practice this split also lets a build frontend supply its own source implementation while still reusing the destination helpers.
On the writing side, WheelDestination declares write_script, write_file and finalize_installation. SchemeDictionaryDestination is the batteries-included implementation. It is a dataclass with a scheme_dict, an interpreter, a script_kind, a hash_algorithm defaulting to sha256, optional bytecode_optimization_levels, an optional destdir, and overwrite_existing. Because these are constructor fields, a caller can swap the hash algorithm or turn on overwrite behavior without subclassing.
RECORD as a Contract, Not an Afterthought
The RECORD file is the wheel’s manifest, and this library treats it as data rather than text. parse_record_file uses csv.reader with a comma delimiter and a double-quote character, requires exactly three fields per row, and normalizes backslashes to forward slashes. Each row becomes a RecordEntry holding a path, an optional Hash, and an optional integer size.
Hash.validate recomputes the digest with hashlib.new, encodes it with base64.urlsafe_b64encode, strips the = padding, and compares strings. RecordEntry.validate_stream avoids buffering an entire file in memory by copying the stream into os.devnull while hashing it; if a size is present it checks the byte count, otherwise it trusts the hash. This is the mechanism behind the CLI’s --validate-record flag, which accepts none, entries, or all.
Design decisions show up in the validation rules. The RECORD row for RECORD itself must not carry a hash or size. Digital signature files such as RECORD.p7s and RECORD.jws must not appear in RECORD at all, because they sign the file rather than being installed content. Every other archive member must have a matching row, and when content validation is enabled, the bytes must agree.
Writing is equally explicit. construct_record_file sorts entries by path, builds CSV rows, and applies a per-scheme prefix so that entries from scripts or data are expressed relative to the root scheme. finalize_installation writes that stream through the same write_to_fs path used for ordinary files, then optionally compiles bytecode with compileall for each requested optimization level. The RECORD is therefore not a side effect of extraction; it is the last deliberate write.
Exit Points: Eight Launchers and a Shebang Hack
Console scripts are where platform differences become visible. parse_entrypoints reads console_scripts and gui_scripts from entry_points.txt, extracts the module and attribute with a compiled regular expression, and strips the _scripts suffix to obtain the section name. Script.generate then chooses a launcher. On POSIX it returns shebang + b"\n" + code; on Windows it prepends one of eight bundled .exe files selected by section and architecture, then appends a zip archive containing __main__.py.
The generated code is deliberately short: it imports the target, resets sys.argv[0] with removesuffix(".exe"), and calls sys.exit(target()). The Windows path matters because a .exe launcher must know which interpreter to start, and the appended zip supplies the Python payload without requiring a separate script file.
Shebang construction is the most defensive part of the file. _is_executable_simple accepts the direct #! form only when the executable contains no space and the resulting line is at most 127 characters. Otherwise _build_shebang emits a /bin/sh trampoline that uses shlex.quote and exec, a workaround for interpreters installed under paths with spaces. For the scripts scheme, write_file runs fix_shebang, which checks the first eight bytes for #!python, writes a new #!{interpreter} line, and copies the remainder of the stream. Finally, write_script copies the read permission bits into execute bits with mode |= (mode & 0o444) >> 2.
Honest Limits
The scope is narrower than “install Python packages” suggests. There is no source-distribution support in this tree: no sdist.py, no build backend, no metadata generation for source trees. It installs wheels and only wheels. There is also no dependency resolver, no uninstall operation, and no transactional rollback; a failure halfway through a member loop can leave a partially populated scheme, which is exactly why callers often stage through destdir first.
validate_record is opt-in. The CLI defaults to --validate-record none, so a plain python -m installer some.whl does not verify hashes unless you ask it to. Signature files are recognized but not verified. The Windows launchers are prebuilt binaries committed under _scripts, not generated on demand. And overwrite_existing defaults to False, which is safe but can surprise anyone expecting package-manager-style replacement.
Compared with the full pip installer, this library is closer to the wheel-format reference implementation described by the wheel specification. Use it when you need deterministic, inspectable writes into a virtualenv-style prefix; keep a real installer for resolution and dependency policy. Enjoyed this post? Never miss out on future posts by following us