A Python package groups importable modules under an owned namespace, and a module entrypoint can be executed with the interpreter’s -m option.
Python package layout: owned imports and module entrypoints
Operation contract
The self-contained fixture builds a temporary src-layout package with an amount formatter and an __main__ module. A child interpreter receives that exact src directory through an explicit path insertion, then executes the package entrypoint. In an installed application the installation supplies import visibility instead; editing sys.path in a production CLI is not the packaging recommendation.
Failure and ownership boundary
The package directory and source text are authored by this fixture, not downloaded or user supplied. Executing code from an untrusted package is arbitrary code execution. Package names can also collide with standard-library names. Python modules: separate import-time definitions from program execution and Python pyproject.toml: build a wheel and inspect its metadata explain why source layout, import ownership and installation are separate decisions.
Working program
import subprocess
import sys
import tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as directory:
source_root = Path(directory) / "src"
package = source_root / "aitrove_receipts"
package.mkdir(parents=True)
(package / "__init__.py").write_text("", encoding="utf-8")
(package / "amounts.py").write_text('def label(amount):\n return f"minor={amount}"\n', encoding="utf-8")
(package / "__main__.py").write_text('from .amounts import label\nprint(label(125))\n', encoding="utf-8")
launcher = "import sys, runpy; sys.path.insert(0, sys.argv[1]); runpy.run_module('aitrove_receipts', run_name='__main__')"
result = subprocess.run([sys.executable, "-I", "-c", launcher, str(source_root)],
check=True, capture_output=True, text=True, timeout=3)
print(result.stdout.strip())Output
minor=125Costs and limits
Creating this tiny package costs a few filesystem writes and one child startup. Real import and installation costs depend on module contents and dependency graphs; src layout alone does not establish isolation.
Common Mistakes
- A source directory must be installed or deliberately placed on the import path.
- Never run a downloaded package merely to inspect whether its metadata looks plausible.
Connected lessons
Python modules: separate import-time definitions from program execution, Python interpreter and virtual environments: run the intended executable, Python pyproject.toml: build a wheel and inspect its metadata.
Related Python operation checks
Django migrations: generate and apply an owned application schema.
Follow the related contract
Python package resources: read data from a ZIP-backed package, Python zipapp: build an executable archive without bundling an interpreter.
Check this related boundary
Python module cache: repeated imports reuse an owned module object, Python packaging: inspect an imported module origin before using it.
