AI Wiki中文/EN

Environments: identify the interpreter, then test the workload

环境与依赖管理

Inspect real Python and distribution versions, create an empty virtual environment and separate identity checks from execution.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

An activated environment may still be the wrong environment

A terminal prompt shows .venv, NumPy imports, and a colleague’s notebook still fails. The prompt is only a clue. The interpreter might have a different patch version, the notebook might use another kernel, or a required library might be missing from the environment that actually runs the code.

For the AI Wiki examples, the local reference is CPython 3.12.4 with NumPy 1.26.4 and pandas 2.2.3. The repository’s requirements-examples.txt also pins four supporting distributions. That package file does not install or pin the Python executable. A different CPython 3.12 patch release can be a valid separately tested environment, while differing from this exact reference.

We will inspect the running interpreter, compare declared versions, create a genuinely empty temporary virtual environment, and run a small numerical/table workload. Those checks answer different questions; none alone means that every experiment is reproducible.

Separate isolation, identity and behavior

A virtual environment starts from an existing interpreter

Python venv creates an environment with its own package installation directories, based on an existing Python installation. By default it excludes system site packages. Activation changes shell command lookup; using the environment’s Python path directly also works. The documented runtime test is sys.prefix != sys.base_prefix, rather than trusting the prompt or VIRTUAL_ENV. Environments are generally recreated at their destination, not copied as portable folders. Python venv

Creating a venv does not select a different Python release or automatically install NumPy. It also does not isolate a kernel, filesystem, GPU driver or network service. This chapter uses a Python virtual environment; its experiment does not build or run a container.

Version pins describe a requested installation

The reference package list is:

DistributionVersion
numpy1.26.4
pandas2.2.3
python-dateutil2.9.0.post0
pytz2026.2
six1.16.0
tzdata2024.1

Pinning only top-level packages leaves room for their dependencies to change. Pinning all requested distributions narrows that variation. Artifact hashes constrain the downloaded files further; retaining suitable wheels also helps when an index is unavailable. Compiled wheels can be platform-specific. The project’s version-pinned text file contains no artifact hashes and is not a complete cross-platform environment lock. pip repeatable installs

The example compares strings exactly. Let R contain the expected field/value pairs for the Python implementation, Python version and six selected distributions, and let O contain their observed pairs. The difference identifies expected items that do not match; the report also supplies each observed value:

Δ=R∖O,matches reference  ⟺  Δ=∅.\Delta=R\setminus O,\qquad \mathrm{matches\ reference}\iff\Delta=\varnothing.

This includes the Python implementation and patch version. It is identity checking for a declared subset, not dependency resolution or a judgment that every differing version is incompatible. Extra installed distributions are outside its comparison scope.

Metadata compatibility is not execution

importlib.metadata reads installed distribution metadata. A distribution name need not equal the import name: python-dateutil, for instance, is a distribution identifier. Metadata discovery is not proof that an extension imports successfully or that a particular numerical operation works. Package metadata

python -m pip check asks whether installed distributions satisfy their declared dependencies. It does not run a project’s tests. A separate smoke test should exercise the behavior the project needs. pip check

Our tiny workload solves a well-conditioned linear system and processes a nullable integer column:

(2112)(x1x2)=(33),(x1,x2)=(1,1).\begin{pmatrix}2&1\\1&2\end{pmatrix}\begin{pmatrix}x_1\\x_2\end{pmatrix}=\begin{pmatrix}3\\3\end{pmatrix},\qquad (x_1,x_2)=(1,1).

The table values [0, missing, 6] contain two known measurements with subtotal six. A residual tolerance of 1e-12 is chosen for this specific small system, not all linear algebra workloads.

Collect evidence from the interpreter that runs the code

Run the complete program with the intended environment’s Python. The package workload requires NumPy and pandas; the inspector and empty-environment probe use the standard library. In the checked local environment, Python is 3.12.4, NumPy 1.26.4 and pandas 2.2.3. The output below avoids machine-specific paths and patch-version values so it can also be checked on another tested CPython 3.12 environment.

observe returns actual version strings, interpreter path, prefixes, system and machine. audit accepts that unmodified result or the same declared schema; it returns explicit mismatches and a separate venv flag. It does not repair, install or remove anything. Missing distributions are represented by None.

fresh_venv_probe creates and deletes a temporary environment with system site packages disabled and no pip bootstrap. It invokes that environment’s Python directly in isolated mode, with no package downloads. The synthetic reports at the end are labeled as such; they demonstrate a patch difference and a missing distribution without changing the real installation.

from importlib import metadata
from pathlib import Path
from tempfile import TemporaryDirectory
import copy
import json
import platform
import subprocess
import sys
import venv


EXPECTED = {
    'implementation': 'CPython', 'python': '3.12.4',
    'packages': {'numpy': '1.26.4', 'pandas': '2.2.3',
                 'python-dateutil': '2.9.0.post0', 'pytz': '2026.2',
                 'six': '1.16.0', 'tzdata': '2024.1'},
}


def observe():
    packages = {}
    for name in EXPECTED['packages']:
        try:
            packages[name] = metadata.version(name)
        except metadata.PackageNotFoundError:
            packages[name] = None
    return {'implementation': platform.python_implementation(),
            'python': platform.python_version(), 'packages': packages,
            'executable': sys.executable, 'prefix': sys.prefix,
            'base_prefix': sys.base_prefix,
            'system': platform.system(), 'machine': platform.machine()}


def audit(observed):
    # Expects an unmodified observe() result or the same declared schema.
    fields = ('implementation', 'python')
    differences = []
    for field in fields:
        actual = observed[field]
        if actual != EXPECTED[field]:
            differences.append((field, EXPECTED[field], actual))
    for name, wanted in sorted(EXPECTED['packages'].items()):
        actual = observed['packages'].get(name)
        if actual != wanted:
            differences.append((name, wanted, actual))
    return {'matches_reference': not differences,
            'differences': differences,
            'uses_venv': observed['prefix'] != observed['base_prefix']}


def fresh_venv_probe():
    # Create an empty environment, without pip or package downloads.
    probe = '''import json, platform, sys
from importlib import metadata
packages = {}
for name in ('numpy', 'pandas'):
    try:
        packages[name] = metadata.version(name)
    except metadata.PackageNotFoundError:
        packages[name] = None
print(json.dumps({'python': platform.python_version(),
                  'uses_venv': sys.prefix != sys.base_prefix,
                  'packages': packages}))
'''
    with TemporaryDirectory(prefix='aiwiki-env-example-') as name:
        location = Path(name) / 'empty'
        venv.EnvBuilder(system_site_packages=False, with_pip=False).create(location)
        executable = location / ('Scripts/python.exe' if sys.platform == 'win32' else 'bin/python')
        completed = subprocess.run([str(executable), '-I', '-B', '-c', probe],
                                   check=True, capture_output=True, text=True)
        return json.loads(completed.stdout)


def smoke():
    # A real workload, deliberately separate from distribution metadata checks.
    import numpy as np
    import pandas as pd
    matrix = np.array([[2.0, 1.0], [1.0, 2.0]])
    target = np.array([3.0, 3.0])
    solution = np.linalg.solve(matrix, target)
    residual = float(np.max(np.abs(matrix @ solution - target)))
    values = pd.Series(pd.array([0, None, 6], dtype='Int64'))
    subtotal = int(values.sum(min_count=1))
    return {'solution': solution.tolist(), 'residual': residual,
            'known': int(values.count()), 'subtotal': subtotal,
            'passes': residual <= 1e-12 and subtotal == 6 and values.count() == 2}


def main():
    actual = observe()
    actual_audit = audit(actual)
    empty = fresh_venv_probe()
    result = smoke()
    # Synthetic reports demonstrate diagnostics; they are not live observations.
    reference = {'implementation': 'CPython', 'python': '3.12.4',
                 'packages': dict(EXPECTED['packages']),
                 'prefix': '/example/venv', 'base_prefix': '/example/base'}
    changed = copy.deepcopy(reference)
    changed['python'] = '3.12.5'
    changed['packages']['numpy'] = None
    print('recorded package names:', sorted(actual['packages']))
    print('fresh venv / same Python:', empty['uses_venv'], empty['python'] == actual['python'])
    print('fresh venv packages:', empty['packages'])
    print('workload / known / subtotal:', result['passes'], result['known'], result['subtotal'])
    print('synthetic reference:', audit(reference)['matches_reference'])
    print('synthetic differences:', audit(changed)['differences'])
    # Return actual host-specific evidence without making it portable stdout.
    return {'observed': actual, 'audit': actual_audit, 'empty': empty, 'smoke': result}


if __name__ == '__main__':
    main()

Output in the tested environment:

recorded package names: ['numpy', 'pandas', 'python-dateutil', 'pytz', 'six', 'tzdata']
fresh venv / same Python: True True
fresh venv packages: {'numpy': None, 'pandas': None}
workload / known / subtotal: True 2 6
synthetic reference: True
synthetic differences: [('python', '3.12.4', '3.12.5'), ('numpy', '1.26.4', None)]

The fresh environment uses the same Python version, yet has neither NumPy nor pandas installed. This separates interpreter selection from package installation. The numerical/table workload runs in the original environment and passes its stated checks. None in the synthetic difference list means missing metadata, not version zero.

To inspect the actual machine-specific report interactively, evaluate audit(observe()); main() also returns the observed fields and audit. An Ubuntu interpreter on another 3.12 patch will correctly report its difference from 3.12.4, even if the workload passes. The portable output is not an assertion that all hosts match the reference.

For a new project environment, create it from the intended Python executable and install with that environment’s interpreter, for example path/to/environment/python -m pip install -r requirements-examples.txt. The executable path differs on Windows and POSIX. Calling pip by an unrelated shell path may target a different interpreter. After installation, run its -m pip check and the project’s relevant tests. These are reconstruction instructions; the program above performs no installation.

With q requested distribution names, the explicit comparison is O(q log q) because package names are sorted, using O(q) returned state. Metadata discovery and creating a venv also involve filesystem work whose cost depends on the installation. The workload here has fixed size. This accounting does not make environment creation constant-time or certify package-download speed.

A passing audit is scoped evidence

The reference manifest is not an inventory of every installed package. It omits pip’s own version from equality checking, and it does not inspect dependency constraint expressions, wheel hashes, build flags, shared libraries or drivers. System and machine are recorded but not judged equal. Metadata can also be stale, and a same-named local import can differ from the installed distribution a metadata query describes. Inspect actual imports when diagnosing that situation.

The smoke test covers one solve and one nullable reduction. It cannot establish that all NumPy and pandas operations work, that a workload is fast, or that a long stochastic training run has identical outputs. Add tests for the behavior that matters to the actual project, including numerical tolerances and data invariants.

Version pins and immutable artifacts aid reconstruction, but a successful install also needs compatible interpreter and platform builds. Keep the requirements source and tested interpreter information in version control, recreate disposable environments, and retain necessary external artifacts separately. An environment folder is not a substitute for that recipe.

This example uses trusted local tooling and its own short probe. A virtual environment manages Python packages; it is not a security boundary for untrusted code.

Read each check at its actual strength

  1. Explain the empty environment. Why does the temporary venv keep the Python version but lose NumPy and pandas?
Separate interpreter and site packages

Answer: It is built on the current interpreter while creating separate package directories and excluding system site packages. The program installs nothing there. Selecting a Python release and installing distributions are separate steps.

  1. Interpret a patch mismatch. The observed interpreter is CPython 3.12.5, while the reference says 3.12.4. What does this program conclude?
Identity is stricter than compatibility

Answer: It lists the Python mismatch and reports that the exact reference does not match. It does not conclude that 3.12.5 is incompatible. Run the required tests and record that interpreter as a separately validated environment if appropriate.

  1. Combine checks. pip check succeeds, but importing a compiled package fails. Is that contradictory?
Metadata and loading are different operations

Answer: No. Declared package dependency requirements can be satisfied while binary loading or an application operation fails. Use the actual environment’s interpreter to reproduce the import and workload failure; a metadata check is not a test suite.

  1. Strengthen a recipe. Does a file containing all six == pins preserve Python, package artifact bytes and GPU drivers?
Locate what the pins do not name

Answer: No. It requests six distribution versions. Record the interpreter separately; hashes and retained platform-appropriate artifacts constrain package bytes; relevant system and driver details need their own record. This chapter did not run a GPU or container experiment.

Use installation records together with executable checks

The venv reference explains package isolation and interpreter identity. The pip installation guide distinguishes version pins, artifact hashes and retained installation bundles. Package metadata and pip check provide observable installation facts; workload tests establish a different kind of evidence.

Git and reproducibility covers source and artifact identity. Numerical code testing explains how to choose a meaningful result check. Together, these pieces turn “it runs on my machine” into a recipe another person can inspect and test.

Make a prediction, then check

An exact 3.12.4 reference differs from an observed CPython 3.12.5, while the workload passes. What is justified?

Choose one answer

Learning objectives

  • Distinguish the base interpreter, isolated package directories and shell activation.
  • Compare a declared version subset while reporting actual runtime identity and its limits.
  • Use installation metadata and an actual workload as separate evidence.

Prerequisites & connections

Explore related knowledge →

References

  1. venv — Python 3.12 documentation
    Python Software Foundation
  2. Repeatable Installs — pip documentation
    pip developers
  3. importlib.metadata — Python 3.12 documentation
    Python Software Foundation
  4. pip check — pip documentation
    pip developers

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-06 · Codex technical check: primary-source locations, original runnable models, independent mathematical and computational references, bilingual review and second-agent cross-checks; not independent human peer review.

  • Eight tests pass on local CPython 3.12.4 / NumPy 1.26.4 / pandas 2.2.3. Runtime identity assertions use the executing host, not a hardcoded patch or path. Six synthetic reports match an independent name/version set-difference oracle; exact spelling, missing packages, extra-package scope and no input mutation are covered. Synthetic 3.12.5 is not claimed as an executed interpreter. Independent AI review corrected the R/O definition to include implementation and Python version, matching audit rather than only package pins.
  • Tests create and remove two empty no-pip venvs and verify unchanged Python version with NumPy/pandas absent. The actual solve matches closed-form (1,1), residual <=1e-12; nullable counts/subtotal are 2/6. Import guards separate metadata discovery from workload imports, including an explicitly injected load failure. The misleading VIRTUAL_ENV marker does not control prefix-based detection.
  • Original complete bilingual program and six stdout lines match; strict MDX/KaTeX plus actual React HTML pass with two displays, six anchors and four answers. Host identity stays in the returned report. Written means AI author checks only; no package installation, global changes, container/GPU execution or whole-site acceptance. Reviewed manifest-subset, non-lock, compatibility and workload limitations.
  • Root read complete bilingual prose and program. After review, the author expanded R/O to include Python implementation/version as well as distributions; a package-only difference had not captured the program’s full predicate. Final frozen text and formula now agree with audit. Code is unchanged.
  • Eight author tests and strict MDX/KaTeX/React HTML pass: two displays, six anchors, four answers. Actual temporary venv creation and NumPy/pandas workload ran under the project interpreter. Host identity tests use runtime values; synthetic differences remain labeled. Five frozen hashes verified.
  • Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
  • Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.

Source locations checked:

  • venv — Python 3.12 documentation · Actually read Python /3.12 venv page rendered 3.12.13: lines 8–19 base-Python package directories and disposable/nonportable scope; 31–35 creation behavior; 95–123 system-site-packages, prefix/base_prefix, direct invocation, activation and relocation limits; 129–140 EnvBuilder options. The actual probe uses with_pip=False and system_site_packages=False in TemporaryDirectory; no install or container was executed.
  • Repeatable Installs — pip documentation · Actually read live pip repeatable-installs page rendered 26.2.1, lines 81–105 for levels of repetition, complete version pins and artifact hashes, and 107–127 for retained wheelhouse and platform limitations. The local requirements-examples.txt was read directly: six pins exactly as printed, no hashes. It does not pin the Python executable. This reference is not represented as the local pip 24.0 documentation.
  • importlib.metadata — Python 3.12 documentation · Actually read fixed /3.12 importlib.metadata page rendered 3.12.13, lines 8–14 for installed distributions and non-one-to-one import names, 20–45 for version lookup and PackageNotFoundError. Program separately imports and exercises NumPy/pandas; metadata matching is never treated as successful binary loading.
  • pip check — pip documentation · Actually read live pip check page rendered 26.2.1, lines 83–107 for invocation and declared dependency compatibility with exit zero, and 118–149 for missing/wrong dependency failures. Separately ran project .venv/bin/python -m pip check with actual pip 24.0: No broken requirements found, exit zero. The read-only command warned that the user cache directory was unavailable and disabled caching; no dependency change was performed.
  • venv — Python 3.12 documentation · Root read venv reference prefix/base_prefix identity, direct invocation, VIRTUAL_ENV limitations and general non-portability (lines 101–121).
  • Repeatable Installs — pip documentation · Root read version pinning, artifact hashes and wheelhouse platform limits (repeatable-installs lines 99–125).
  • importlib.metadata — Python 3.12 documentation · Root read distribution metadata versus import names (lines 10–13) and inspected actual version lookup without importing workloads.
  • pip check — pip documentation · Root read pip check Description line 97: declared installed dependency compatibility; no workload execution guarantee.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.