Trending

World technology news

→
Distributing a field-reporting tool as a single archive with Python 3.5 zipapp
Software Engineering · 2015
Software Engineering2015

Distributing a field-reporting tool as a single archive with Python 3.5 zipapp

A two-module meter utility illustrates Python 3.5’s packaging tool, archive entry points, external input paths and runtime requirements.

Archive retrospective · Topic year 2015

Developer's JournalPublished: Dec 5, 20266 min read
Reading progress0%
In this article
  1. The problem with distributing a folder of scripts
  2. Keep the entry point separate from the data path
  3. Run it from outside the source directory
  4. Account for every dependency in the archive
  5. Make paths outside the archive explicit
  6. Check the interpreter used on the recipient machine
  7. Verify the business rule after a release

The problem with distributing a folder of scripts

A small utility that totals readings on a factory floor may start out as a script and a helper module. If those two files are copied independently, a machine can end up running a new script against old business rules. Python 3.5 added zipapp to the standard library, as documented in its September 2015 release notes and in PEP 441. It provides a way to distribute an entry point and its supporting code as one ZIP application. In this example, the archive contains the counting rule and takes a JSON file as an external input. The program and its input can be updated independently, and a user can run another file through the same copy of the utility.

Keep the entry point separate from the data path

Python executes the archive’s root __main__.py when the file is invoked as an application. The example entry point reads the input path from the command line, opens the JSON and imports the counting rule from rules.py. The rule excludes negative readings. In a production application their interpretation would come from the measurement schema. Here the negative reading distinguishes the expected output of 42 from 41, the result obtained by adding all three values. Packaging stores both code files in the archive. The input remains a separate file, and the test uses its absolute path. The zipapp module can also generate an entry point from a module and callable named during packaging.

Application flowConceptual sketch · summary of the article's technical flow

Run it from outside the source directory

I ran the example locally with Python 3.12.10. The script writes two source files in a temporary directory and builds meter.pyz with zipapp.create_archive. It then starts a separate interpreter in isolated mode from outside the source directory, passing both the archive and the input path. The subprocess exits successfully and prints 42 for the values 14, minus 1 and 28. Running outside the source directory helps ensure the test actually uses the modules included in the archive. This run exercises the current interpreter and standard library. Python 3.5 introduced the feature, but a machine that still targets that release needs an acceptance run with its own interpreter.

from pathlib import Path
from tempfile import TemporaryDirectory
import subprocess
import sys
import zipapp

entry = """import json
import sys
from rules import total
with open(sys.argv[1], encoding="utf-8") as stream:
    values = json.load(stream)
print(total(values))
"""
with TemporaryDirectory() as folder:
    root = Path(folder)
    project = root / "src"
    project.mkdir()
    (project / "rules.py").write_text(
        "def total(values):\n    return sum(value for value in values if value >= 0)\n",
        encoding="utf-8",
    )
    (project / "__main__.py").write_text(entry, encoding="utf-8")
    archive = root / "meter.pyz"
    zipapp.create_archive(project, archive)
    source = root / "samples.json"
    source.write_text("[14, -1, 28]", encoding="utf-8")
    result = subprocess.run(
        [sys.executable, "-I", str(archive), str(source.resolve())],
        cwd=root, stdout=subprocess.PIPE, check=True,
    )
    assert result.stdout.decode().strip() == "42"
    print("ZIP application:", result.stdout.decode().strip())
    print("Python", sys.version.split()[0])

Account for every dependency in the archive

The utility uses only the standard library and its own helper. A larger project can include third-party pure Python modules, provided the publisher resolves the appropriate versions and includes the required files and notices. The zipapp module does not perform that dependency management. Native extensions such as C-based modules generally need to be installed outside the archive or handled through a different distribution layout so that the platform can load their shared libraries. Commands started by the utility must also exist on the target machine. Identify which packages, programs, Python versions and filesystem permissions the tool expects before handing it to another team. A smaller archive is useful when those expectations are documented and independently checked.

Make paths outside the archive explicit

A machine may invoke the utility from a desktop shortcut, a scheduler or a terminal in the download folder. Each entry point can choose a different working directory. Imports from the archive and relative input paths follow different mechanisms. The example takes an explicit input argument so callers can choose the full path. A practical command-line tool can report the failing path with an input error and use a designated output directory for its report. Output outside the archive also gives operators a predictable place to inspect permissions and retention. A fixed acceptance fixture should stay separate from operational readings so the packaged utility can be tested in isolation from production data.

Check the interpreter used on the recipient machine

An archive can contain an interpreter directive for environments that support direct execution. This example deliberately invokes a known Python executable. On Windows, a scheduler can store the interpreter and archive paths explicitly, which reduces dependence on file associations. An archive packages the application's Python code, while language syntax and library behavior still depend on the selected runtime. Test versions and installation layouts actually used by recipients with a fixture that has a known answer. Capturing an archive checksum in the release record can help teams associate those test results with the binary they received. Keep an older interpreter test separate from a current one when historical compatibility matters.

Verify the business rule after a release

An acceptance fixture should exercise a real rule, with an ordinary input, a boundary and a case that gets filtered out. The example distinguishes between old and new counting behavior by checking the exact output of 42. A deployed utility can also test invalid input, a missing data file, and a location it cannot write to. Decide what partial output means before processing a batch of independent files. Then record the application release and input identity with those errors so an operator can retry the affected file under the same rule. The archive makes it easier to distribute one set of rules, while the fixture determines whether that set was actually used.

Further reading / Referencehttps://peps.python.org/pep-0441/ ↗
691 reads ✎ Write a comment

Reader discussion

Discussion prompt

What would you change first for maintainability and testing in your own project?

No comments yet. Be the first to contribute.

Write a comment

Comments are real visitor contributions. Repeated, link-heavy or abusive submissions may be limited.