Typorithm · medium

Install the artifact and run outside the checkout

pythonlibrariespackagingindependent-practice
Saved on this device
Full lesson · 4 learning steps Open any exercise for focused practice
1

Step 1 of 4 · intro card

Install the artifact and run outside the checkout

0%

Concept and contract

Verify a wheel in a clean environment with isolated imports, packaged resources and real command-line arguments.

Tests run from a repository can accidentally import local files that are absent from the built artifact. A clean installation outside that repository checks a different boundary: what another application or command-line user actually receives. Src layout makes this distinction easier to preserve.

The driver builds the owned wheel, creates a fresh virtual environment and installs only that exact local file with no package index and no dependencies. It then launches the package from another directory using isolated Python imports. The initial lab tool installation is separate; this verification does not fetch packages while testing the built distribution.

Mechanism and worked example

The fixture package contains reusable selection logic, a CLI module, a __main__ delegate and a defaults resource.

The fixture package contains reusable selection logic, a CLI module, a __main__ delegate and a defaults resource. The displayed project files show those separate responsibilities. The driver sends rows as JSON on standard input and passes the inclusive minimum as an explicit command-line option.

The installed command returns sorted unique identifiers and the chosen minimum. A boundary-equal score remains included, zero stays meaningful and an empty input returns an empty identifier list. Running outside the project prevents a missing wheel file from being silently supplied by the source tree during this observation.

Complete worked example

python

import json
from pathlib import Path
import subprocess
import sys
import venv

def inspect_example(rows, minimum):
    project = Path('project').resolve()
    subprocess.run([sys.executable, '-m', 'build', '--no-isolation', '--wheel', '--outdir', 'dist'],
                   cwd=project, capture_output=True, text=True, check=True)
    wheel = next((project / 'dist').glob('*.whl'))
    environment = Path('installed').resolve()
    venv.EnvBuilder(with_pip=True).create(environment)
    python = environment / ('Scripts/python.exe' if sys.platform == 'win32' else 'bin/python')
    subprocess.run([str(python), '-I', '-m', 'pip', 'install', '--no-index', '--no-deps', str(wheel)],
                   capture_output=True, text=True, check=True)
    outside = Path('outside').resolve()
    outside.mkdir()
    command = [str(python), '-I', '-m', 'pye_owned', '--minimum', str(minimum)]
    run = subprocess.run(command, cwd=outside, input=json.dumps(rows),
                         capture_output=True, text=True, check=True)
    return json.loads(run.stdout)
Reasoning
The fixture package contains reusable selection logic, a CLI module, a __main__ delegate and a defaults resource. The displayed project files show those separate responsibilities. The driver sends rows as JSON on standard input and passes the inclusive minimum as an explicit command-line option.
Download the reusable Python and packaging computer lab ↗

Focused decision: use the complete example for context

bash

python -I -m pip install --no-index --no-deps path/to/owned_report.whl
python -I -m pye_owned --minimum 2
Decision
Install the exact built artifact into a fresh environment outside the source tree and add an explicit descending-order flag.

Owned project file: src/pye_owned/cli.py

python

import argparse
from importlib.resources import files
import json
import sys
from .contracts import selected_ids


def main() -> int:
    defaults = json.loads(files("pye_owned").joinpath("defaults.json").read_text(encoding="utf-8"))
    parser = argparse.ArgumentParser()
    parser.add_argument("--minimum", type=int, default=defaults["minimum"])
    parser.add_argument("--descending", action="store_true")
    args = parser.parse_args()
    try:
        rows = json.load(sys.stdin)
        if not isinstance(rows, list):
            raise ValueError("input must be a list")
        ids = selected_ids(rows, args.minimum)
    except (ValueError, AttributeError, TypeError) as error:
        print(str(error), file=sys.stderr)
        return 2
    if args.descending:
        ids.reverse()
    print(json.dumps({"ids": ids, "minimum": args.minimum}, sort_keys=True))
    return 0
Owned project fixture
This exact file is included in the downloaded lab and in the fresh project used by the executable acceptance cases. Read it alongside the complete driver.
Download the reusable Python and packaging computer lab ↗

Owned project file: src/pye_owned/__main__.py

python

from .cli import main

raise SystemExit(main())
Owned project fixture
This exact file is included in the downloaded lab and in the fresh project used by the executable acceptance cases. Read it alongside the complete driver.
Download the reusable Python and packaging computer lab ↗

Counterexamples and common mistakes

The counterexample passes minimum plus one to the installed command.

The counterexample passes minimum plus one to the installed command. The package still runs successfully and returns valid JSON, but its selected identifiers and reported threshold no longer match the caller's contract. A zero exit code is therefore insufficient acceptance evidence.

An editable installation would weaken this particular test because it can keep pointing at local source files. Editable mode is useful during development, but the release check should install the built wheel. Similarly, omitting isolated imports or remaining inside the checkout can make the test pass for the wrong source location.

Controlled bug: the executable contract rejects this version

python

import json
from pathlib import Path
import subprocess
import sys
import venv

def inspect_example(rows, minimum):
    project = Path('project').resolve()
    subprocess.run([sys.executable, '-m', 'build', '--no-isolation', '--wheel', '--outdir', 'dist'],
                   cwd=project, capture_output=True, text=True, check=True)
    wheel = next((project / 'dist').glob('*.whl'))
    environment = Path('installed').resolve()
    venv.EnvBuilder(with_pip=True).create(environment)
    python = environment / ('Scripts/python.exe' if sys.platform == 'win32' else 'bin/python')
    subprocess.run([str(python), '-I', '-m', 'pip', 'install', '--no-index', '--no-deps', str(wheel)],
                   capture_output=True, text=True, check=True)
    outside = Path('outside').resolve()
    outside.mkdir()
    command = [str(python), '-I', '-m', 'pye_owned', '--minimum', str(minimum + 1)]
    run = subprocess.run(command, cwd=outside, input=json.dumps(rows),
                         capture_output=True, text=True, check=True)
    return json.loads(run.stdout)
Reasoning
The counterexample passes minimum plus one to the installed command. The package still runs successfully and returns valid JSON, but its selected identifiers and reported threshold no longer match the caller's contract. A zero exit code is therefore insufficient acceptance evidence.
Download the reusable Python and packaging computer lab ↗

Independent practice

Pass the owned CLI's descending flag while retaining the explicit minimum.

Pass the owned CLI's descending flag while retaining the explicit minimum. Preserve unique filtering and return the identifiers in descending order. The first hint is to add the supported flag to the subprocess argument list rather than reversing the caller's row collection.

The second hint is to keep checking the reported minimum independently of order. Empty input remains empty, and a single zero-score identifier remains present at minimum zero. Do not alter the library's inclusive threshold to achieve a different order; filtering and presentation direction are separate command-line decisions.

Step 1: Install the exact built artifact into a fresh environment outside the source tree and add an explicit descending-order flag. Step 2: Run the accepted baseline, edit the exercise, then check its independent solution cases; preserve caller inputs and the documented exception behavior.

Practice starter: solve before reading the solution

python

import json
from pathlib import Path
import subprocess
import sys
import venv

def inspect_example(rows, minimum):
    project = Path('project').resolve()
    subprocess.run([sys.executable, '-m', 'build', '--no-isolation', '--wheel', '--outdir', 'dist'],
                   cwd=project, capture_output=True, text=True, check=True)
    wheel = next((project / 'dist').glob('*.whl'))
    environment = Path('installed').resolve()
    venv.EnvBuilder(with_pip=True).create(environment)
    python = environment / ('Scripts/python.exe' if sys.platform == 'win32' else 'bin/python')
    subprocess.run([str(python), '-I', '-m', 'pip', 'install', '--no-index', '--no-deps', str(wheel)],
                   capture_output=True, text=True, check=True)
    outside = Path('outside').resolve()
    outside.mkdir()
    command = [str(python), '-I', '-m', 'pye_owned', '--minimum', str(minimum)]
    run = subprocess.run(command, cwd=outside, input=json.dumps(rows),
                         capture_output=True, text=True, check=True)
    return json.loads(run.stdout)

# Task: Install the exact built artifact into a fresh environment outside the source tree and add an explicit descending-order flag.
# Practice contract: Install the exact built artifact into a fresh environment outside the source tree and add an explicit descending-order flag.
Reasoning
Install the exact built artifact into a fresh environment outside the source tree and add an explicit descending-order flag.
Download the reusable Python and packaging computer lab ↗
  • Hint 1: Pass the owned CLI's descending flag while retaining the explicit minimum. Preserve unique filtering and return the identifiers in descending order. The first hint is to add the supported flag to the subprocess argument list rather than reversing the caller's row collection.
  • Hint 2: The second hint is to keep checking the reported minimum independently of order. Empty input remains empty, and a single zero-score identifier remains present at minimum zero. Do not alter the library's inclusive threshold to achieve a different order; filtering and presentation direction are separate command-line decisions.

Solution, tests and trade-offs

The solution adds the descending option to the installed package invocation.

The solution adds the descending option to the installed package invocation. Acceptance checks a multi-identifier case that exposes direction, an empty case and a zero-boundary case. The package code still reads its defaults resource before parsing the explicit option, so installation also exercises shipped resource access.

Fresh environments take more work than direct function calls and should complement rather than replace fast unit tests. Use them at the artifact boundary where their evidence matters. The lab keeps all project directories and environments temporary and owned, while the app receives only the verified static examples and prepared results.

Practice solution and acceptance checks

python

import json
from pathlib import Path
import subprocess
import sys
import venv

def inspect_example(rows, minimum):
    project = Path('project').resolve()
    subprocess.run([sys.executable, '-m', 'build', '--no-isolation', '--wheel', '--outdir', 'dist'],
                   cwd=project, capture_output=True, text=True, check=True)
    wheel = next((project / 'dist').glob('*.whl'))
    environment = Path('installed').resolve()
    venv.EnvBuilder(with_pip=True).create(environment)
    python = environment / ('Scripts/python.exe' if sys.platform == 'win32' else 'bin/python')
    subprocess.run([str(python), '-I', '-m', 'pip', 'install', '--no-index', '--no-deps', str(wheel)],
                   capture_output=True, text=True, check=True)
    outside = Path('outside').resolve()
    outside.mkdir()
    command = [str(python), '-I', '-m', 'pye_owned', '--descending', '--minimum', str(minimum)]
    run = subprocess.run(command, cwd=outside, input=json.dumps(rows),
                         capture_output=True, text=True, check=True)
    return json.loads(run.stdout)
Reasoning
The solution adds the descending option to the installed package invocation. Acceptance checks a multi-identifier case that exposes direction, an empty case and a zero-boundary case. The package code still reads its defaults resource before parsing the explicit option, so installation also exercises shipped resource access.
Download the reusable Python and packaging computer lab ↗

Interview reasoning and next step

Explain why successful tests from the checkout can coexist with a broken wheel.

Explain why successful tests from the checkout can coexist with a broken wheel. Then identify the roles of no-index installation, no-deps installation, isolated imports and the outside working directory in this owned dependency-free fixture. Avoid claiming those flags supply missing runtime dependencies for a real third-party project.

For a stretch, deliberately omit the CLI module from a copied package and compare a source-tree test with the installed-wheel invocation. Capture the actual failure and restore the fixture afterward. Keep command arguments as a subprocess list so filenames and values are passed explicitly rather than interpreted as shell syntax.

Optional stretch — after the core task works: For a stretch, deliberately omit the CLI module from a copied package and compare a source-tree test with the installed-wheel invocation. Capture the actual failure and restore the fixture afterward. Keep command arguments as a subprocess list so filenames and values are passed explicitly rather than interpreted as shell syntax.

Computer practice: https://applydjinn.com/typorithm/python-engineering-lab-20261107.zip. Use an isolated Python 3.13 environment, install requirements.txt, then run verify.py. Edit exercises/pye-cli.py and run --practice pye-cli. Fixture files are created in fresh temporary directories for every case. Packaging checks build real local artifacts, install the exact wheel without an index and run outside the source tree. No package is published to PyPI. The app includes static examples, prepared results and questions; it does not run Python or provide an editor.

Verify a wheel in a clean environment with isolated imports, packaged resources and real command-line arguments.