Typorithm · medium

Capstone: a reusable report package with a verified console entry point

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

Step 1 of 4 · intro card

Capstone: a reusable report package with a verified console entry point

0%

Concept and contract

Deliver one small library and CLI, then verify metadata, resources, boundaries and installed behavior together.

The capstone joins the course's boundaries in one owned package: a reusable function validates rows, a CLI owns JSON and arguments, resource data supplies defaults and distribution metadata declares an installed command. Each layer has a different reason to change.

The project files shown across these packaging lessons are part of the downloadable lab, and every acceptance case receives a fresh copy. The installed report contract requires unique sorted identifiers whose scores meet an inclusive threshold. It preserves zero, handles empty input and rejects malformed rows in the package's explicit validation path.

Mechanism and worked example

The driver builds and installs the exact local wheel into a fresh environment, then runs the generated pye-report console command from an outside directory.

The driver builds and installs the exact local wheel into a fresh environment, then runs the generated pye-report console command from an outside directory. This verifies the declared entry-point target rather than merely importing its function in the checkout.

A separate isolated interpreter reads the installed distribution version through importlib.metadata. The returned report therefore combines actual command output and actual installed metadata. The first case includes a duplicate identifier and a score exactly at the minimum, making both deduplication and inclusivity observable without contacting any external API.

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()
    script = environment / ('Scripts/pye-report.exe' if sys.platform == 'win32' else 'bin/pye-report')
    command = [str(script), '--minimum', str(minimum)]
    run = subprocess.run(command, cwd=outside, input=json.dumps(rows),
                         capture_output=True, text=True, check=True)
    metadata = subprocess.run([str(python), '-I', '-c',
        "from importlib.metadata import version; print(version('applydjinn-owned-report'))"],
        cwd=outside, capture_output=True, text=True, check=True)
    return {'report': json.loads(run.stdout), 'version': metadata.stdout.strip()}
Reasoning
The driver builds and installs the exact local wheel into a fresh environment, then runs the generated pye-report console command from an outside directory. This verifies the declared entry-point target rather than merely importing its function in the checkout.
Download the reusable Python and packaging computer lab ↗

Focused decision: use the complete example for context

text

[project.scripts]
pye-report = "pye_owned.cli:main"
Decision
Verify the installed console entry point, version metadata, resource data, duplicate handling and inclusive threshold together.

Owned project file: src/pye_owned/contracts.py

python

def selected_ids(rows: list[dict[str, object]], minimum: int) -> list[str]:
    if type(minimum) is not int:
        raise ValueError("minimum must be an integer")
    selected = set()
    for row in rows:
        identity, score = row.get("id"), row.get("score")
        if not isinstance(identity, str) or not identity or type(score) is not int:
            raise ValueError("each row needs a nonempty id and an integer score")
        if score >= minimum:
            selected.add(identity)
    return sorted(selected)
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/__init__.py

python

from .contracts import selected_ids

__all__ = ["selected_ids"]
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/defaults.json

json

{"minimum": 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.

Counterexamples and common mistakes

The controlled bug passes a larger minimum to the console command.

The controlled bug passes a larger minimum to the console command. The process still resolves its installed entry point, reads resources and emits JSON, yet the caller-visible report changes. Packaging success cannot compensate for a wrong domain decision at the invocation boundary.

Likewise, a correct library function alone would not prove that the wheel includes its CLI, defaults resource or entry-point metadata. The preceding lessons isolate those concerns; the capstone verifies them together. Keep both levels of evidence so a combined success is understandable and a future failure can be located precisely.

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()
    script = environment / ('Scripts/pye-report.exe' if sys.platform == 'win32' else 'bin/pye-report')
    command = [str(script), '--minimum', str(minimum + 1)]
    run = subprocess.run(command, cwd=outside, input=json.dumps(rows),
                         capture_output=True, text=True, check=True)
    metadata = subprocess.run([str(python), '-I', '-c',
        "from importlib.metadata import version; print(version('applydjinn-owned-report'))"],
        cwd=outside, capture_output=True, text=True, check=True)
    return {'report': json.loads(run.stdout), 'version': metadata.stdout.strip()}
Reasoning
The controlled bug passes a larger minimum to the console command. The process still resolves its installed entry point, reads resources and emits JSON, yet the caller-visible report changes. Packaging success cannot compensate for a wrong domain decision at the invocation boundary.
Download the reusable Python and packaging computer lab ↗

Independent practice

Add consoleEntryPoint to the returned observation and prove the generated command is a file in the fresh environment.

Add consoleEntryPoint to the returned observation and prove the generated command is a file in the fresh environment. Preserve command execution, selected identifiers, minimum and installed version. The first hint is to reuse the actual script path selected for the current platform.

The second hint is to check that path after installation, not a similarly named source file. Existence alone is insufficient, so the original subprocess execution must remain part of the solution. The empty and zero-boundary cases still matter after adding packaging evidence: installation checks must not replace the report's behavioral contract.

Step 1: Verify the installed console entry point, version metadata, resource data, duplicate handling and inclusive threshold together. 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()
    script = environment / ('Scripts/pye-report.exe' if sys.platform == 'win32' else 'bin/pye-report')
    command = [str(script), '--minimum', str(minimum)]
    run = subprocess.run(command, cwd=outside, input=json.dumps(rows),
                         capture_output=True, text=True, check=True)
    metadata = subprocess.run([str(python), '-I', '-c',
        "from importlib.metadata import version; print(version('applydjinn-owned-report'))"],
        cwd=outside, capture_output=True, text=True, check=True)
    return {'report': json.loads(run.stdout), 'version': metadata.stdout.strip()}

# Task: Verify the installed console entry point, version metadata, resource data, duplicate handling and inclusive threshold together.
# Practice contract: Verify the installed console entry point, version metadata, resource data, duplicate handling and inclusive threshold together.
Reasoning
Verify the installed console entry point, version metadata, resource data, duplicate handling and inclusive threshold together.
Download the reusable Python and packaging computer lab ↗
  • Hint 1: Add consoleEntryPoint to the returned observation and prove the generated command is a file in the fresh environment. Preserve command execution, selected identifiers, minimum and installed version. The first hint is to reuse the actual script path selected for the current platform.
  • Hint 2: The second hint is to check that path after installation, not a similarly named source file. Existence alone is insufficient, so the original subprocess execution must remain part of the solution. The empty and zero-boundary cases still matter after adding packaging evidence: installation checks must not replace the report's behavioral contract.

Solution, tests and trade-offs

The solution retains end-to-end execution and adds a concrete existence observation for the installed command.

The solution retains end-to-end execution and adds a concrete existence observation for the installed command. Acceptance includes duplicate identifiers, an empty report, a rejected low score and an included zero score. Installed version remains one point zero point zero for this fixture.

The generated command delegates to cli.main, while __main__.py supports python -m pye_owned through the same function. Both reuse contracts.selected_ids and packaged defaults. A production release would additionally need its own supported-platform matrix and distribution process; the lab proves this bounded local artifact without publishing a package or adding an execution runtime to the phone.

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()
    script = environment / ('Scripts/pye-report.exe' if sys.platform == 'win32' else 'bin/pye-report')
    command = [str(script), '--minimum', str(minimum)]
    run = subprocess.run(command, cwd=outside, input=json.dumps(rows),
                         capture_output=True, text=True, check=True)
    metadata = subprocess.run([str(python), '-I', '-c',
        "from importlib.metadata import version; print(version('applydjinn-owned-report'))"],
        cwd=outside, capture_output=True, text=True, check=True)
    return {'report': json.loads(run.stdout), 'version': metadata.stdout.strip(), 'consoleEntryPoint': script.is_file()}
Reasoning
The solution retains end-to-end execution and adds a concrete existence observation for the installed command. Acceptance includes duplicate identifiers, an empty report, a rejected low score and an included zero score. Installed version remains one point zero point zero for this fixture.
Download the reusable Python and packaging computer lab ↗

Interview reasoning and next step

Review the package as another developer would: explain its import API, accepted data, CLI entry point, defaults resource and installed version.

Review the package as another developer would: explain its import API, accepted data, CLI entry point, defaults resource and installed version. Then identify which acceptance observation would fail if filtering, packaging or command registration regressed. State the limits of the tested interpreter and platform.

For a stretch, add an owned configuration option and verify it through direct library tests and the installed command. Rebuild and reinstall the artifact instead of relying on editable source. Keep the new option explicit in the contract, and use a separate local distribution name before considering any real publication outside this teaching project.

Optional stretch — after the core task works: For a stretch, add an owned configuration option and verify it through direct library tests and the installed command. Rebuild and reinstall the artifact instead of relying on editable source. Keep the new option explicit in the contract, and use a separate local distribution name before considering any real publication outside this teaching project.

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-capstone.py and run --practice pye-capstone. 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.

Deliver one small library and CLI, then verify metadata, resources, boundaries and installed behavior together.