DEV Community

Wenlo
Wenlo

Posted on AI-assisted

Package a Python example and prove the restored copy still works

A ZIP file existing is not the same as a usable handoff. This example packages only the three named files from the Day 19 fictional project, restores them into a disposable folder, checks their bytes and runs the restored tests in a separate process.

Run the example

I ran this example in PythonIDE on an English iPhone simulator using only the supplied fictional project files. Save the script as day20/package_handoff.py. Keep day19/project beside day20, with parser_core.py and check_project.py from Day 19 and a plain README.md describing the example.

from pathlib import Path
from tempfile import TemporaryDirectory
import hashlib
import json
import subprocess
import sys
import zipfile

# Only the three explicit fictional project files are read.
project = Path(__file__).resolve().parent.parent / 'day19' / 'project'
names = ['parser_core.py', 'check_project.py', 'README.md']
if not all((project / name).is_file() for name in names):
    raise FileNotFoundError('Keep the Day19 project beside this lesson')
files = {name: (project / name).read_bytes() for name in names}
manifest = {name: hashlib.sha256(data).hexdigest()
            for name, data in files.items()}

with TemporaryDirectory(prefix='handoff-lesson-') as temp:
    root = Path(temp)
    archive = root / 'example.zip'
    with zipfile.ZipFile(archive, 'w', zipfile.ZIP_DEFLATED) as z:
        for name, data in files.items():
            z.writestr(name, data)
        z.writestr('manifest.json', json.dumps(manifest, indent=2))
    restored = root / 'restored'
    restored.mkdir()
    with zipfile.ZipFile(archive) as z:
        expected = set(names) | {'manifest.json'}
        assert set(z.namelist()) == expected
        # Whitelisted flat names only, no arbitrary extractall.
        for name in expected:
            (restored / name).write_bytes(z.read(name))
    saved = json.loads((restored / 'manifest.json').read_text())
    for name in names:
        actual = hashlib.sha256((restored / name).read_bytes()).hexdigest()
        assert actual == saved[name] == manifest[name]
    print('Archive contents and SHA-256 checks passed.')
    # Embedded runners may not add the script folder to sys.path.
    bootstrap = (
        'import runpy, sys; '
        f'sys.path.insert(0, {str(restored)!r}); '
        f'runpy.run_path({str(restored / "check_project.py")!r}, '
        'run_name="__main__")'
    )
    result = subprocess.run(
        [sys.executable, '-c', bootstrap],
        cwd=restored, text=True, capture_output=True)
    print(result.stdout)
    print(result.stderr)
    if result.returncode:
        raise RuntimeError('Restored project checks failed')
    print('Restored project passed in a separate Python process.')
print('Temporary archive removed; source project unchanged.')
Enter fullscreen mode Exit fullscreen mode

PythonIDE editor showing the explicit file list, SHA-256 manifest and ZIP creation

PythonIDE editor showing restoration, checksum validation and the separate test process

Read the behavior and its boundaries

The explicit file list prevents an accidental “zip everything” operation from including unrelated notes, caches or secrets. SHA-256 values detect whether the restored files match the originals. They do not authenticate an author: someone who changes both a file and its manifest can still create a self-consistent archive.

Restoration accepts only the known flat names and does not call extractall on arbitrary archive paths. The final test run happens against the restored copy, not the source tree, which catches missing-file and import assumptions that a source-only test can miss. The archive is temporary and removed after the check; this script demonstrates verification rather than distributing anything.

The example requires the Day 19 folder and subprocess support. If the runtime does not allow a child interpreter, manually run the restored tests in the supported app workflow rather than treating the automatic check as passed.

Observed run: archive contents and SHA-256 checks passed, then all four restored tests passed. The bootstrap explicitly adds the restored folder to sys.path: the initial run without this step exposed a missing-module error in the embedded runner. Setting a working directory alone is not a portable substitute for configuring imports.

PythonIDE console showing verified checksums, four passing restored tests, and cleanup

Try one change

Deliberately omit parser_core.py from the archive list and observe which check catches the missing dependency. Then restore it and explain why checksum verification and behavioral tests answer different questions.

I build PythonIDE, a Python coding app for iPhone and iPad. AI assisted with drafting and translation; the source, archive checks and restored tests were checked in PythonIDE on an iPhone simulator.

View on the App Store

Top comments (0)