Know which environment changes
A working pip command can install into the wrong Python. A successful install can also leave the wrong versions or an incomplete dependency set. This lesson makes those decisions observable before later lessons depend on the tools.
Use the executable approved and checked in lesson 1. The exercised route is macOS 15.7.9 ARM64, zsh, final standard GIL-enabled CPython 3.15.1. Linux, Windows and other build routes remain unverified for this walkthrough. No administrator command, cloud account or paid service is needed. Permission to use the approved interpreter and fetch these public packages is required.
You will create a fresh owned root, two disposable virtual environments and a private wheel directory. Initial acquisition contacts files.pythonhosted.org over HTTPS and downloads about 8.9 MB. Installed environments use more space. This is not a measured minimum disk/RAM allowance. All six required text files appear in full below; no prior author cache or hidden download is needed. Copy them with your editor as plain UTF-8 files.
A virtual environment has its own package installation directory while using a base Python. A distribution is an installed package release such as pytest; its distribution name need not equal an import name. A wheel is a built distribution archive. A lock file here lists exact releases and the accepted SHA-256 digest of each selected wheel. It is an authored requirements file, not the output of a new lockfile tool or a portable selection for every OS.
Separate executable, package location and availability
| Evidence | Meaning |
|---|---|
| Base executable | Approved interpreter used to create the environment |
| Environment executable | Explicit .venv/bin/python selects this environment |
| sys.prefix | Current installation prefix; must be the expected owned environment |
| sys.base_prefix | Base interpreter prefix; differs while running in a venv |
| Distribution metadata | Installed names, versions and locations; not an audit of every installed byte |
| pip check | Declared dependency requirements are consistent; not a behavior or security assessment |
Activation adjusts a shell's PATH for convenience. It is unnecessary when every command names the environment executable. The checks below use the prefix, not the resolved interpreter symlink: on this Mac, resolving .venv/bin/python can lead back to the base binary while the invocation still selects the venv.
The five direct tools are pytest 9.1.1, mypy 2.4.0, Hypothesis 6.170.9, build 1.6.1 and Hatchling 1.32.4. Fourteen additional distributions, including pip 26.2.2, complete the selected set of nineteen. Tools are installed and identified here; their test/check/build techniques are taught before later use. The smaller official pure-Python mypy wheel is deliberately selected instead of its compiled wheel at the same version. Other selected wheels carry macOS ARM64/CPython tags, so changing only a filename for another platform is invalid.
Create and mark the root
In zsh, select the approved path again. Replace the quoted executable only if your already checked approved path differs:
AP_PYTHON='/opt/homebrew/bin/python3.15' &&
"$AP_PYTHON" -VV &&
AP_TOOL_ROOT="$(mktemp -d -t advanced-python-toolchain)" &&
printf '%s\n' 'advanced-python:lesson-2' > "$AP_TOOL_ROOT/.advanced-python-owner" &&
cd "$AP_TOOL_ROOT" &&
pwd
Stop if creation or cd fails. Retain the exact printed path, keep this terminal open, and save only this lesson's files there. The shell variables name the selected executable and owned directory; they do not activate an environment. A closed terminal needs those exact values restored before resuming.
The inventory will be the marker, acquire_wheels.py, check_env.py, check_versions.py, reset_owned.py, wheels.json and requirements.lock, plus the created wheelhouse, .venv and .rebuild directories. No personal documents or secrets belong here. The marker catches ordinary mistakes; it is not a security sandbox for an untrusted directory, script or manifest.
Supply the exact artifact selection
Save the complete wheels.json below. JSON uses quoted field names, commas between entries and square brackets for the list. Each row names one version, its wheel filename, publisher-hosted URL, expected byte count and SHA-256 digest. The URL and digest were checked against that release's PyPI JSON metadata; the pip URL/digest also agree with Python's 3.15.1 release page. These are content fingerprints from those sources, not independent publisher attestation.
[
{
"name": "ast_serialize",
"version": "0.13.1",
"filename": "ast_serialize-0.13.1-cp315-abi3.abi3t-macosx_11_0_arm64.whl",
"url": "https://files.pythonhosted.org/packages/23/c4/a8a2ca21e3943555b48221f8fba546877a7ad39efaf6505506524967d7c4/ast_serialize-0.13.1-cp315-abi3.abi3t-macosx_11_0_arm64.whl",
"sha256": "68f8829d114dab6c9db4a8bbb8d0e342958faee1b5e15a29022678df639960f8",
"bytes": 1222214
},
{
"name": "build",
"version": "1.6.1",
"filename": "build-1.6.1-py3-none-any.whl",
"url": "https://files.pythonhosted.org/packages/ad/9b/9fb3585dabcd73a1b2a6267f63f62649347c9e6d072c9fde365b105abb2c/build-1.6.1-py3-none-any.whl",
"sha256": "ecd351a4be9d35a9eaaba244a7687143c9c7d4aea6ac964e7e7ddab20cbcf4e7",
"bytes": 31179
},
{
"name": "hatchling",
"version": "1.32.4",
"filename": "hatchling-1.32.4-py3-none-any.whl",
"url": "https://files.pythonhosted.org/packages/5f/80/91f51f439c05d4ec4623c22928ce16a938d6d793bf709477830823497859/hatchling-1.32.4-py3-none-any.whl",
"sha256": "08ecf7548fb48205e7f213d70c71e67b8271b7242093dc3f1da578b42c734a2c",
"bytes": 78748
},
{
"name": "hypothesis",
"version": "6.170.9",
"filename": "hypothesis-6.170.9-cp315-abi3.abi3t-macosx_11_0_arm64.whl",
"url": "https://files.pythonhosted.org/packages/7c/3c/b5d1de16483963961cd953f9258439c9757ee843b44a50850608a18a3053/hypothesis-6.170.9-cp315-abi3.abi3t-macosx_11_0_arm64.whl",
"sha256": "271fee69af9c68af7898d176c2cb668a9a841e8f670f8a1c766fda05fafd177e",
"bytes": 789937
},
{
"name": "iniconfig",
"version": "2.3.1",
"filename": "iniconfig-2.3.1-py3-none-any.whl",
"url": "https://files.pythonhosted.org/packages/56/43/4ca9e49d27a1fcf6bece6f6aec0ea46bb9112489b93d4b688fb415457bdb/iniconfig-2.3.1-py3-none-any.whl",
"sha256": "9121e2c1fdb355232495be3194c8dfe87ccc2d5dee45947b78e68f499790d7a7",
"bytes": 7552
},
{
"name": "librt",
"version": "0.16.0",
"filename": "librt-0.16.0-cp315-cp315-macosx_11_0_arm64.whl",
"url": "https://files.pythonhosted.org/packages/8e/30/a90ca13f1d3d91af1680000a4038536907018fbd51764767287a05d28b8b/librt-0.16.0-cp315-cp315-macosx_11_0_arm64.whl",
"sha256": "8ff5d26c529336be9bd7ae04483235d77778ee7d6444a95353102b542601ce81",
"bytes": 154522
},
{
"name": "mypy",
"version": "2.4.0",
"filename": "mypy-2.4.0-py3-none-any.whl",
"url": "https://files.pythonhosted.org/packages/81/12/46ae8670c98a3cd0286ca5645c2f918f8f6be65edfed81b916010619f668/mypy-2.4.0-py3-none-any.whl",
"sha256": "d01c5d26a352acc6d5cf3128225477e1e8465e8d3029d4c345807fbf7f3cf093",
"bytes": 2800734
},
{
"name": "mypy_extensions",
"version": "1.1.0",
"filename": "mypy_extensions-1.1.0-py3-none-any.whl",
"url": "https://files.pythonhosted.org/packages/79/7b/2c79738432f5c924bef5071f933bcc9efd0473bac3b4aa584a6f7c1c8df8/mypy_extensions-1.1.0-py3-none-any.whl",
"sha256": "1be4cccdb0f2482337c4743e60421de3a356cd97508abadd57d47403e94f5505",
"bytes": 4963
},
{
"name": "packaging",
"version": "26.3",
"filename": "packaging-26.3-py3-none-any.whl",
"url": "https://files.pythonhosted.org/packages/63/34/ba1c580383c9eada3711951fef0795c80b829a078d72188184bcab9dd527/packaging-26.3-py3-none-any.whl",
"sha256": "d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c",
"bytes": 129956
},
{
"name": "pathspec",
"version": "1.1.1",
"filename": "pathspec-1.1.1-py3-none-any.whl",
"url": "https://files.pythonhosted.org/packages/f1/d9/7fb5aa316bc299258e68c73ba3bddbc499654a07f151cba08f6153988714/pathspec-1.1.1-py3-none-any.whl",
"sha256": "a00ce642f577bf7f473932318056212bc4f8bfdf53128c78bbd5af0b9b20b189",
"bytes": 57328
},
{
"name": "pip",
"version": "26.2.2",
"filename": "pip-26.2.2-py3-none-any.whl",
"url": "https://files.pythonhosted.org/packages/3f/06/3e4420302363fbb71be3c7f35ce042f54bfca330e3e66b3a2e3c4cca579f/pip-26.2.2-py3-none-any.whl",
"sha256": "fd7f4dfa8190e014013b9f08f3e973f4e4c26ffd179a204895533a7254813a70",
"bytes": 1819850
},
{
"name": "pluggy",
"version": "1.7.0",
"filename": "pluggy-1.7.0-py3-none-any.whl",
"url": "https://files.pythonhosted.org/packages/40/9e/2b38731e0fc536806f16490e1a12d7f0dc2a1235aa8cc07bcc75416a7daa/pluggy-1.7.0-py3-none-any.whl",
"sha256": "7dd7b0d8832ba3cb632c306926ded123429211b83641b35dc5c41ad2d34f9bec",
"bytes": 27082
},
{
"name": "Pygments",
"version": "2.21.0",
"filename": "pygments-2.21.0-py3-none-any.whl",
"url": "https://files.pythonhosted.org/packages/71/46/17f022dd3e953bf20a04a028a21ec746d942f8d2af30fa0f124fa0e6a684/pygments-2.21.0-py3-none-any.whl",
"sha256": "2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9",
"bytes": 1250147
},
{
"name": "pyproject_hooks",
"version": "1.3.3",
"filename": "pyproject_hooks-1.3.3-py3-none-any.whl",
"url": "https://files.pythonhosted.org/packages/85/11/044d1ae1b4ec0d7af88ee5bc91e081be1022533032b906a7bdabdbb60977/pyproject_hooks-1.3.3-py3-none-any.whl",
"sha256": "5fc53fdac9f7bd63fbcdc868fb5f90b4784d78a53a3d3388cd738b807441a20b",
"bytes": 10724
},
{
"name": "pytest",
"version": "9.1.1",
"filename": "pytest-9.1.1-py3-none-any.whl",
"url": "https://files.pythonhosted.org/packages/24/25/1de2678b631f5a49215c6c96fff41ba892b0a34df68d6d80292b1b48aa7f/pytest-9.1.1-py3-none-any.whl",
"sha256": "37a86b45efb9a47a61a36449063e8e18d0cab3161329fc099eb21783169c4f0c",
"bytes": 386536
},
{
"name": "sortedcontainers",
"version": "2.4.0",
"filename": "sortedcontainers-2.4.0-py2.py3-none-any.whl",
"url": "https://files.pythonhosted.org/packages/32/46/9cb0e58b2deb7f82b84065f37f3bffeb12413f947f9388e4cac22c4621ce/sortedcontainers-2.4.0-py2.py3-none-any.whl",
"sha256": "a163dcaede0f1c021485e957a39245190e74249897e2ae4b2aa38595db237ee0",
"bytes": 29575
},
{
"name": "tomlkit",
"version": "0.15.2",
"filename": "tomlkit-0.15.2-py3-none-any.whl",
"url": "https://files.pythonhosted.org/packages/da/46/7d84138a60a8bd796825b2d38ebe92d0d16501ca57d501b7c5d677401bbc/tomlkit-0.15.2-py3-none-any.whl",
"sha256": "05562412163a3037b94497385fb7f9204c637bc605af7a48199e41cf2272f437",
"bytes": 52225
},
{
"name": "trove-classifiers",
"version": "2026.9.21.13",
"filename": "trove_classifiers-2026.9.21.13-py3-none-any.whl",
"url": "https://files.pythonhosted.org/packages/30/81/0da8afb52a71d0a4f2bd3152357b1a441e393b286374802b9d3addab4ab5/trove_classifiers-2026.9.21.13-py3-none-any.whl",
"sha256": "8b1ff4f9c191b1040b71c37f1e445ab99732911e3cd91de52838453a854d7a17",
"bytes": 14232
},
{
"name": "typing_extensions",
"version": "4.16.0",
"filename": "typing_extensions-4.16.0-py3-none-any.whl",
"url": "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl",
"sha256": "481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8",
"bytes": 45571
}
]
A digest is calculated from file contents. The 64 hexadecimal characters name the accepted content, not a secret. A different digest means stop and diagnose; calculating a new hash from an unexplained replacement does not approve it. Trust in this manifest and its consulted sources is a separate assumption.
Save requirements.lock exactly as follows. == pins a distribution version;
--hash=sha256: permits the selected artifact. All direct and transitive
requirements are listed: a later resolver may not silently add an unhashed
package or choose another artifact. This file intentionally includes pip.
ast_serialize==0.13.1 --hash=sha256:68f8829d114dab6c9db4a8bbb8d0e342958faee1b5e15a29022678df639960f8
build==1.6.1 --hash=sha256:ecd351a4be9d35a9eaaba244a7687143c9c7d4aea6ac964e7e7ddab20cbcf4e7
hatchling==1.32.4 --hash=sha256:08ecf7548fb48205e7f213d70c71e67b8271b7242093dc3f1da578b42c734a2c
hypothesis==6.170.9 --hash=sha256:271fee69af9c68af7898d176c2cb668a9a841e8f670f8a1c766fda05fafd177e
iniconfig==2.3.1 --hash=sha256:9121e2c1fdb355232495be3194c8dfe87ccc2d5dee45947b78e68f499790d7a7
librt==0.16.0 --hash=sha256:8ff5d26c529336be9bd7ae04483235d77778ee7d6444a95353102b542601ce81
mypy==2.4.0 --hash=sha256:d01c5d26a352acc6d5cf3128225477e1e8465e8d3029d4c345807fbf7f3cf093
mypy_extensions==1.1.0 --hash=sha256:1be4cccdb0f2482337c4743e60421de3a356cd97508abadd57d47403e94f5505
packaging==26.3 --hash=sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c
pathspec==1.1.1 --hash=sha256:a00ce642f577bf7f473932318056212bc4f8bfdf53128c78bbd5af0b9b20b189
pip==26.2.2 --hash=sha256:fd7f4dfa8190e014013b9f08f3e973f4e4c26ffd179a204895533a7254813a70
pluggy==1.7.0 --hash=sha256:7dd7b0d8832ba3cb632c306926ded123429211b83641b35dc5c41ad2d34f9bec
Pygments==2.21.0 --hash=sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9
pyproject_hooks==1.3.3 --hash=sha256:5fc53fdac9f7bd63fbcdc868fb5f90b4784d78a53a3d3388cd738b807441a20b
pytest==9.1.1 --hash=sha256:37a86b45efb9a47a61a36449063e8e18d0cab3161329fc099eb21783169c4f0c
sortedcontainers==2.4.0 --hash=sha256:a163dcaede0f1c021485e957a39245190e74249897e2ae4b2aa38595db237ee0
tomlkit==0.15.2 --hash=sha256:05562412163a3037b94497385fb7f9204c637bc605af7a48199e41cf2272f437
trove-classifiers==2026.9.21.13 --hash=sha256:8b1ff4f9c191b1040b71c37f1e445ab99732911e3cd91de52838453a854d7a17
typing_extensions==4.16.0 --hash=sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8
Keep both files together. wheels.json supplies acquisition URLs; requirements.lock supplies pip's accepted installation set. The later inventory check compares installed releases against that complete lock, including unexpected extras.
Acquire and verify before executing a wheel
Save the complete original acquire_wheels.py:
import hashlib
import json
from pathlib import Path
import subprocess
import sys
root = Path.cwd()
owner = root / ".advanced-python-owner"
if not owner.is_file() or owner.read_text(encoding="utf-8").strip() != "advanced-python:lesson-2":
raise SystemExit("STOP: use the marked lesson-2 root.")
if sys.argv[1:] not in ([], ["--offline"]):
raise SystemExit("Usage: acquire_wheels.py [--offline]")
offline = sys.argv[1:] == ["--offline"]
rows = json.loads(Path("wheels.json").read_text(encoding="utf-8"))
if len(rows) != 19:
raise SystemExit("STOP: the complete manifest has 19 artifacts.")
cache = root / "wheelhouse"
if cache.is_symlink():
raise SystemExit("STOP: wheelhouse must not be a symlink.")
cache.mkdir(exist_ok=True)
for row in rows:
name = row["filename"]
if Path(name).name != name or not name.endswith(".whl"):
raise SystemExit("STOP: invalid wheel filename.")
if not row["url"].startswith("https://files.pythonhosted.org/packages/"):
raise SystemExit("STOP: unexpected artifact origin.")
target = cache / name
if target.is_symlink():
raise SystemExit("STOP: a cached wheel is a symlink.")
if target.exists():
data = target.read_bytes()
else:
if offline:
raise SystemExit("MISSING: " + name)
part = cache / (name + ".part")
if part.is_symlink():
raise SystemExit("STOP: partial file is a symlink.")
try:
subprocess.run(
["/usr/bin/curl", "--disable", "--fail", "--location", "--proto", "=https",
"--proto-redir", "=https", "--connect-timeout", "10",
"--max-time", "45", "--retry", "0", "--silent", "--show-error",
"--output", str(part), row["url"]],
check=True, timeout=50,
)
data = part.read_bytes()
if len(data) != row["bytes"] or hashlib.sha256(data).hexdigest() != row["sha256"]:
raise SystemExit("MISMATCH: " + name)
part.replace(target)
finally:
part.unlink(missing_ok=True)
if len(data) != row["bytes"] or hashlib.sha256(data).hexdigest() != row["sha256"]:
raise SystemExit("MISMATCH: " + name)
print("verified:", name, flush=True)
print("wheels: verified", len(rows))
The marker check runs before creating the cache. json.loads turns the supplied
JSON into rows. The fixed count catches a truncated list; filename/origin checks
bound ordinary path mistakes, and symlink checks reject redirected cache paths.
This helper expects the trusted supplied files, not hostile manifests.
For each row, an existing wheel is read and rehashed. In offline mode, a missing
wheel stops immediately. Otherwise subprocess.run starts the fixed macOS curl
executable with a list of arguments, so no shell evaluates the URL. --disable
ignores a personal curl configuration; HTTPS and HTTPS redirects are required.
Connection time is bounded at ten seconds, each transfer at forty-five and the
child process at fifty. There are no automatic retries: at most nineteen bounded
fetches occur. These are operation bounds, not a promise of a specific total
wall-clock duration under arbitrary filesystem/process failures.
curl writes a .part file. Only a matching size and digest allow replace to
publish its final filename. The finally block runs cleanup when this attempt
leaves its try block, including the ordinary error path; missing_ok=True also
handles a partial file already renamed away. An abrupt machine/process loss may
leave a .part file. Stop acquisition before inspecting it; the next normal fetch
replaces that owned partial path. A cached mismatch stops rather than silently
accepting or repairing suspicious bytes. The script does not execute a wheel.
Run from the marked root using the approved base Python:
"$AP_PYTHON" -I -B acquire_wheels.py
-I isolates Python's import path from user-site and PYTHONPATH settings; -B
avoids bytecode-cache writes for the helpers. Expect nineteen verified: lines
followed by wheels: verified 19. A complete rerun rehashes the cached files
without contacting the network. --offline additionally refuses missing files:
"$AP_PYTHON" -I -B acquire_wheels.py --offline
A TLS, transfer, missing-file or digest error is unsuccessful. Do not proceed with installation after such a result. Network access may require your normal approved network/proxy setup; do not disable certificate verification as a fix.
Create an empty environment and prove its identity
Save check_env.py:
from pathlib import Path
import site
import sys
root = Path.cwd().resolve()
owner = root / ".advanced-python-owner"
if not owner.is_file() or owner.read_text(encoding="utf-8").strip() != "advanced-python:lesson-2":
raise SystemExit("STOP: use the marked lesson-2 root.")
if len(sys.argv) != 2 or sys.argv[1] not in (".venv", ".rebuild"):
raise SystemExit("Usage: check_env.py .venv OR .rebuild")
expected = root / sys.argv[1]
print("executable:", sys.executable)
print("prefix:", sys.prefix)
print("base_prefix:", sys.base_prefix)
if (sys.implementation.name != "cpython"
or sys.version_info[:3] != (3, 15, 1)
or sys.version_info.releaselevel != "final"):
raise SystemExit("STOP: final CPython 3.15.1 required.")
if sys.abi_info.free_threaded or not sys._is_gil_enabled():
raise SystemExit("STOP: standard GIL-enabled build required.")
if (expected.is_symlink() or Path(sys.prefix).resolve() != expected
or sys.prefix == sys.base_prefix or site.ENABLE_USER_SITE):
raise SystemExit("STOP: wrong or non-isolated environment.")
config = (expected / "pyvenv.cfg").read_text(encoding="utf-8")
if "include-system-site-packages = false" not in config:
raise SystemExit("STOP: system site packages must remain excluded.")
print("environment: matched", sys.argv[1])
The script accepts only the two names used in this exercise. It reports the running executable and prefixes, requires the same final standard build as lesson 1, then compares the actual prefix with the expected root. A base Python or a different venv is rejected. User-site access and system-site inclusion must remain disabled. The pyvenv.cfg check inspects the generated environment setting; it does not authenticate the underlying base binary.
Now create .venv and check it. && runs the next command only after a zero
(success) exit from the preceding command. These groups stop at a failed gate
instead of continuing into installation. Run one group at a time and inspect each
result before the next group. Use a fresh destination; do not create over an
old partial environment.
"$AP_PYTHON" -I -m venv --without-pip "$AP_TOOL_ROOT/.venv" &&
"$AP_TOOL_ROOT/.venv/bin/python" -I -B check_env.py .venv
-m venv invokes the standard-library module. --without-pip skips the normal
ensurepip bootstrap; no tool package has been installed yet. The successful
report ends environment: matched .venv; sys.prefix names this owned .venv and
sys.base_prefix names its base. Paths vary, but their relationship must agree.
Why this bootstrap route? On the author-tested distribution, the installed
ensurepip wheel's SHA-256 was
b67ada3ed1aad866bb855203157d354a39ef06590635d43f24ebab68ea00a9f7,
while the release-linked/PyPI pip wheel is
fd7f4dfa8190e014013b9f08f3e973f4e4c26ffd179a204895533a7254813a70.
That observed difference remains unexplained; it does not identify a cause or
establish a compromise. This narrowly checked walkthrough bypasses that bundled
artifact. ensurepip and get-pip.py are the pip maintainers' usual supported
bootstrap mechanisms; executing the verified wheel through Python's import
path is the author-tested alternative here, not a general production guarantee.
Bootstrap pip, then install the complete lock
First reverify the files and identity. Then the following command temporarily puts only the verified pip wheel on this Python invocation's PYTHONPATH:
"$AP_PYTHON" -I -B acquire_wheels.py --offline &&
"$AP_TOOL_ROOT/.venv/bin/python" -I -B check_env.py .venv &&
env -u PYTHONHOME PYTHONPATH="$AP_TOOL_ROOT/wheelhouse/pip-26.2.2-py3-none-any.whl" PIP_CONFIG_FILE=/dev/null \
"$AP_TOOL_ROOT/.venv/bin/python" -s -B -m pip --isolated --disable-pip-version-check --no-cache-dir \
install --no-index --no-deps --only-binary=:all: "$AP_TOOL_ROOT/wheelhouse/pip-26.2.2-py3-none-any.whl"
env applies these settings only to this command: it clears an inherited
PYTHONHOME and sets a wheel import path. Python can import a package from this
ZIP-format wheel. -s disables user-site imports; -I is deliberately absent
on this bootstrap invocation because it would ignore PYTHONPATH. -m pip
runs the pip CLI from that verified wheel using the venv executable. This
executes third-party package code, so verification and the identity decision
must come first. No pip internal API is imported by a helper.
PIP_CONFIG_FILE=/dev/null disables configuration files for this invocation;
--isolated ignores ordinary pip environment options/user configuration.
Version checks and pip's shared cache are disabled. --no-index forbids index
lookup; --no-deps installs this one already verified pip wheel only.
--only-binary=:all: disallows source distributions. This first invocation
relies on the explicit prior digest check; the full install also enforces the
lock's hashes. There is no global PYTHONPATH export or shell activation to undo.
Check the installed pip origin, then install the complete set offline:
"$AP_TOOL_ROOT/.venv/bin/python" -I -m pip --version &&
PIP_CONFIG_FILE=/dev/null "$AP_TOOL_ROOT/.venv/bin/python" -I -m pip --isolated --disable-pip-version-check --no-cache-dir \
install --no-index --find-links "$AP_TOOL_ROOT/wheelhouse" --only-binary=:all: --require-hashes -r requirements.lock
Inspect the pip version 26.2.2 and location under this .venv. --find-links
selects candidates in the owned wheel directory; --require-hashes enforces
all supplied pins/hashes. -r reads this root's complete requirements.lock.
Dependency processing is left enabled here so undeclared dependencies fail
rather than being concealed with --no-deps. -I now works because pip is
installed in the environment. A partial/failed install is not a usable checkpoint.
Hashes constrain the artifacts installed in this run. An already installed requirement can be considered satisfied without its wheel being reinstalled or rehashed. The successful rerun below is an idempotence check, not an installed file-integrity audit; the fresh rebuild is needed to exercise artifact selection again. Neither hash matching nor dependency consistency establishes that a third-party package's behavior is safe or suitable for your work.
Verify the result, then rebuild independently
Save check_versions.py:
from importlib.metadata import distributions
from pathlib import Path
import sys
root = Path.cwd().resolve()
owner = root / ".advanced-python-owner"
if not owner.is_file() or owner.read_text(encoding="utf-8").strip() != "advanced-python:lesson-2":
raise SystemExit("STOP: use the marked lesson-2 root.")
if len(sys.argv) != 2 or sys.argv[1] not in (".venv", ".rebuild"):
raise SystemExit("Usage: check_versions.py .venv OR .rebuild")
expected_root = root / sys.argv[1]
if expected_root.is_symlink() or Path(sys.prefix).resolve() != expected_root or sys.prefix == sys.base_prefix:
raise SystemExit("STOP: wrong environment.")
def normalize(name):
return name.lower().replace("_", "-").replace(".", "-")
expected = {}
for line in Path("requirements.lock").read_text(encoding="utf-8").splitlines():
name, version = line.split()[0].split("==")
expected[normalize(name)] = version
actual = {}
for dist in distributions():
name = normalize(dist.metadata["Name"])
if not Path(dist.locate_file("")).resolve().is_relative_to(expected_root):
raise SystemExit("STOP: distribution outside the owned environment: " + name)
if name in actual:
raise SystemExit("STOP: duplicate distribution metadata: " + name)
actual[name] = dist.version
if actual != expected:
print("expected:", expected)
print("actual:", actual)
raise SystemExit("STOP: installed versions differ from the complete lock.")
for name in sorted(actual):
print(name + "==" + actual[name])
print("distributions: matched", len(actual))
importlib.metadata.distributions() reads visible installed-distribution
metadata. The helper normalizes the known names' case/underscore/dot spelling,
extracts pinned versions from the first token of each lock line and compares
the entire name/version map. It rejects duplicate metadata, unexpected versions,
extra visible distributions and metadata locations outside this owned prefix.
This is a version/location check, not content verification of installed modules.
Only after the identity check passed, run:
"$AP_TOOL_ROOT/.venv/bin/python" -I -B check_versions.py .venv &&
PIP_CONFIG_FILE=/dev/null "$AP_TOOL_ROOT/.venv/bin/python" -I -m pip --isolated --disable-pip-version-check check &&
"$AP_TOOL_ROOT/.venv/bin/python" -I -m pytest --version &&
"$AP_TOOL_ROOT/.venv/bin/python" -I -m mypy --version &&
"$AP_TOOL_ROOT/.venv/bin/python" -I -m build --version
Expect nineteen exact name/version lines and distributions: matched 19.
pip check should report No broken requirements found. The version probes
should identify pytest 9.1.1, mypy 2.4.0 and build 1.6.1. Hypothesis 6.170.9 and
Hatchling 1.32.4 are included in the metadata inventory; they do not need
invented version commands. These probes establish availability only.
Repeat the full locked install command in .venv once, then the inventory and pip check. It should leave the selected versions consistent. Next create an independent .rebuild from the same base, using only the verified cache:
"$AP_PYTHON" -I -B acquire_wheels.py --offline &&
"$AP_PYTHON" -I -m venv --without-pip "$AP_TOOL_ROOT/.rebuild" &&
"$AP_TOOL_ROOT/.rebuild/bin/python" -I -B check_env.py .rebuild &&
env -u PYTHONHOME PYTHONPATH="$AP_TOOL_ROOT/wheelhouse/pip-26.2.2-py3-none-any.whl" PIP_CONFIG_FILE=/dev/null \
"$AP_TOOL_ROOT/.rebuild/bin/python" -s -B -m pip --isolated --disable-pip-version-check --no-cache-dir \
install --no-index --no-deps --only-binary=:all: "$AP_TOOL_ROOT/wheelhouse/pip-26.2.2-py3-none-any.whl" &&
PIP_CONFIG_FILE=/dev/null "$AP_TOOL_ROOT/.rebuild/bin/python" -I -m pip --isolated --disable-pip-version-check --no-cache-dir \
install --no-index --find-links "$AP_TOOL_ROOT/wheelhouse" --only-binary=:all: --require-hashes -r requirements.lock &&
"$AP_TOOL_ROOT/.rebuild/bin/python" -I -B check_versions.py .rebuild &&
PIP_CONFIG_FILE=/dev/null "$AP_TOOL_ROOT/.rebuild/bin/python" -I -m pip --isolated --disable-pip-version-check check
Pause if identity or any intermediate command fails; subsequent commands do not repair that failure. Both fresh installs must match the same nineteen releases. This verifies this pinned macOS artifact selection on this runtime, not all OS wheel sets or a claim that the files will remain downloadable indefinitely.
Diagnose before resetting
| Evidence | Next decision |
|---|---|
| Transfer/TLS/timeout failure | Leave verification unsuccessful; inspect the URL/network message and retry the same supplied acquisition later |
| MISSING in offline mode | Acquire the named supplied artifact online; a partial cache is not complete |
| MISMATCH | Stop before execution; compare the trusted manifest and source. Do not approve the replacement by changing its expected hash |
| Wrong prefix or base Python | Select the explicit owned environment executable; installing more packages will not fix interpreter selection |
| No matching distribution / hash error | Check the selected platform/build, complete artifact set and lock; do not remove --require-hashes or enable source builds |
| Version map or pip check differs | Treat environment as incomplete; inspect the installed map and rebuild the exact owned environment |
For a partial install, the simplest recovery is a fresh owned environment from the verified cache. Re-running venv over an old destination does not reset its packages. Do not use sudo, a global pip upgrade or a different platform's wheel as a routine repair.
Check Your Understanding
Attempt before opening the explanation. Keep evidence of the failed boundary as well as the restored success; an old success report is not a current result.
-
From the marked root, invoke check_env.py with the base AP_PYTHON and argument .venv. Predict the prefix relationship and explain why this refuses. Then demonstrate the correct .venv invocation. Do not run a base pip install.
-
From the verified marked root, append one byte to the owned pytest wheel using this complete one-off Python command:
"$AP_PYTHON" -I -c 'from pathlib import Path; wheel = Path("wheelhouse/pytest-9.1.1-py3-none-any.whl"); wheel.write_bytes(wheel.read_bytes() + b"x")'-cruns the quoted Python statements; semicolons separate those statements. read_bytes returns bytes,b"x"is one byte, and write_bytes replaces this exercise's cached copy with the old bytes plus that byte. No new source file is created. Predict the result of offline verification. Run it, identify the named failure and explain why installing must stop. Preserve the unchanged manifest. Restore only the named artifact by deleting its corrupt cached copy after inspection and rerunning acquisition online; verify all 19. -
Copy requirements.lock to wrong-hash.lock and change one hexadecimal character of pytest's hash, leaving its version untouched. First reset and recreate .rebuild only, bootstrap verified pip there and attempt the locked install with
-r wrong-hash.lock. Keep .venv as the working control. Why is a fresh destination important? Restore by resetting .rebuild and installing with the original requirements.lock, then check both environments. -
Explain what the fresh rebuild, version map, pip check and --version probes each establish, and give one thing none of them establishes.
The following helper and procedure are available to perform those exact owned resets; read them before the attempt if needed. They do not reveal the diagnosis.
Reset owned generated directories
Save reset_owned.py:
from pathlib import Path
import shutil
import sys
root = Path.cwd().resolve()
owner = root / ".advanced-python-owner"
if not owner.is_file() or owner.read_text(encoding="utf-8").strip() != "advanced-python:lesson-2":
raise SystemExit("STOP: use the marked lesson-2 root.")
if len(sys.argv) != 2 or sys.argv[1] not in (".venv", ".rebuild", "wheelhouse"):
raise SystemExit("Usage: reset_owned.py .venv OR .rebuild OR wheelhouse")
target = root / sys.argv[1]
if target.is_symlink() or (target.exists() and not target.is_dir()):
raise SystemExit("STOP: expected an ordinary owned directory.")
if target.exists():
shutil.rmtree(target)
print("removed or already absent:", target.name)
The marker and fixed allowlist limit this helper to .venv, .rebuild or wheelhouse
in the current owned root. A top-level symlink or ordinary file at one of those
names is refused. shutil.rmtree recursively removes that selected directory,
including its generated contents; it leaves the other two names and original
source/lock files in place. An already absent target is a successful no-op.
This is an exercise recovery helper, not a security boundary for hostile files.
Before any reset, stop active installs/helpers, return to the exact saved root, and inspect ownership and inventory:
cd "$AP_TOOL_ROOT" &&
pwd &&
cat .advanced-python-owner &&
ls -a
Stop if cd fails, the path is wrong, the marker differs from
advanced-python:lesson-2, or unexpected files need investigation. After that
inspection, an exact environment reset is:
"$AP_PYTHON" -I -B reset_owned.py .rebuild
This intentionally removes the .rebuild packages. Recreate that name using the full sequence above, never by copying or moving .venv. For .venv recovery use that allowed name and repeat its corresponding identity/bootstrap/install checks. Cache reset is separate; removing wheelhouse requires reacquisition online.
Answer and Reasoning
Hint 1: separate the boundaries
Use prefix evidence for selection, wheel contents for digest verification, and a fresh destination for a lock failure. Installing successfully in one environment says nothing about which interpreter another command selects.
Hint 2: preserve the control
Keep .venv working while resetting .rebuild. A corrupt cache is an artifact problem; a changed expected hash is a lock problem. Repair the damaged input against the original trusted source, not by weakening the check.
Compare the evidence
The base invocation reports equal prefix/base_prefix and cannot match the owned .venv prefix. The correct invocation reports the selected owned prefix and a different base. Activation is not required; the explicit path controls it.
Appending a byte changes both size and digest. The helper reports MISMATCH for that wheel before any install. Stop all cache readers, remove only that named corrupt file from this owned wheelhouse, then fetch the original URL again. A missing offline wheel instead reports MISSING. Neither error is fixed by rewriting the trusted digest or treating an old installed environment as proof that the cache is sound.
The changed pytest hash is rejected by pip's required-hash check in a fresh .rebuild. A tool already satisfied in .venv could otherwise skip reinstallation, so a successful rerun there would not demonstrate the faulty lock was exercised. A failed install may leave partial state; reset .rebuild, retain the original requirements.lock and bootstrap/install/check from it. Remove the exercise's wrong-hash.lock after recording its expected failure. There is no source-build or no-hash fallback in this task.
A fresh offline rebuild shows the selected cached artifacts can install on this runtime without an index. The version map checks visible names, versions and metadata locations. pip check checks declared dependency consistency. Version commands show those entry modules can start and identify themselves. None is qualified approval, complete behavioral testing, an audit of installed bytes, independent publisher attestation or proof of another platform's compatibility.
Retain evidence and clean up
Keep the actual base/environment reports, version map, dependency result and failure/recovery explanation outside the disposable root if wanted. Restore the trusted inputs after variations. Stop installs, reset programs and any commands using the environments before deletion. Inspect the root/marker and inventory using the preceding procedure. Then remove only the three generated directories through the fixed helper:
"$AP_PYTHON" -I -B reset_owned.py .venv &&
"$AP_PYTHON" -I -B reset_owned.py .rebuild &&
"$AP_PYTHON" -I -B reset_owned.py wheelhouse
Remove wrong-hash.lock separately if you created it. Inspect again: only the marker and six supplied files should remain. After that confirmed inventory:
rm acquire_wheels.py check_env.py check_versions.py reset_owned.py wheels.json requirements.lock .advanced-python-owner &&
cd .. &&
rmdir "$AP_TOOL_ROOT"
rmdir removes only an empty root and refuses unexpected remaining files. A failed directory change or unexpected inventory is a reason to inspect before deleting. The approved base interpreter remains installed. Later lessons resupply their complete inputs and recreate their owned environments; this lesson's disposable environment is not a hidden carry-forward requirement.
References
- Python 3.15.1 release and verified pip bootstrap artifact
- Homebrew acquisition context
- venv creation, isolation, prefixes and recreation
- pip hash checking and binary-only installs
- pip CLI configuration and isolation
- pip installation options
- pip check's dependency scope
- pip maintainers' bootstrap mechanisms
- Installed distribution metadata
- PyPI JSON metadata API
- SHA-256 hashing
- curl transfer flags and time limits
- Bounded child execution
- Owned directory removal
- ZIP imports
- Interpreter fields and GIL observations
- Path/file operations
- JSON decoding
- Free-threaded build versus current GIL state
Revisit the reasoning in Revision or retrieve the taught procedures in Quick Reference.