Python · Chapter 10 of 21
Python modules, packages, argparse and timeit
14 min study · Examples checked with Python 3.14 and 3.15 ·
Once a script grows past a screen or two, it is time to split it into files. In Python every .py file is a module, and a folder of modules is a package. This chapter turns a small report script into a package with a command-line interface, explains what actually happens during import, and shows how to measure whether a change makes code faster.
How import works
import math
import statistics as stats
from pathlib import Path
print(math.sqrt(81), stats.mean([72, 85, 91])) # 9.0 82.66666666666667
print(Path("notes.txt").suffix) # .txt
print(math.__name__, stats.__name__) # math statistics
import math binds the name math to the module object; you then write math.sqrt. from pathlib import Path binds just Path. as picks a different local name, which is useful for long names and established conventions, and confusing when it invents abbreviations. Avoid from module import *: readers can no longer tell where a name came from, and it can silently overwrite your own names.
The first time a module is imported, Python finds the file, runs all of its top-level code once, and stores the resulting module object in sys.modules. Later imports anywhere in the program reuse that object without running the file again. Two consequences follow. A module’s top-level code should only define things (functions, classes, constants), because anything else, such as opening a database connection or asking for input, happens as a side effect of importing it. And module-level variables are effectively shared across the whole program.
Python looks for modules in the folder of the script being run, then in the standard library and installed packages. A file of your own called json.py, random.py or fastapi.py therefore shadows the real module, with baffling errors as a result. When an import behaves strangely, print(module.__file__) shows which file was loaded.
Build a package
Here is a package called reports with a module of calculations. In a project, these are two files inside a reports folder:
"""Score reports for the study tracker."""
from .calculations import average, grade
__all__ = ["average", "grade"]
def average(scores: list[float]) -> float:
if not scores:
raise ValueError("no scores to average")
return sum(scores) / len(scores)
def grade(score: float) -> str:
return "pass" if score >= 60 else "retry"
__init__.py runs when the package is imported. Here it re-exports the two functions, so users can write from reports import average without knowing which submodule holds it; __all__ documents that public interface. The leading dot in from .calculations import ... is a relative import: “the calculations module in this same package”. Relative imports only work inside a package, which is why packages are run with python -m reports rather than by file path.
from reports import average, grade
import reports.calculations
print(average([72, 85, 91]), grade(59)) # 82.66666666666667 retry
print(reports.calculations.grade(60)) # pass
Make the package runnable with main and argparse
Each module has a __name__. It is the module’s import name, except for the module Python was asked to run, where it is "__main__". The check if __name__ == "__main__": therefore separates “run me” code from “import me” code. For a package, python -m reports runs reports/__main__.py:
import argparse
from . import average, grade
def main(argv: list[str] | None = None) -> None:
parser = argparse.ArgumentParser(prog="reports", description="Summarize quiz scores.")
parser.add_argument("scores", nargs="+", type=float, help="one or more scores")
parser.add_argument("--decimals", type=int, default=1, help="digits after the point")
args = parser.parse_args(argv)
value = average(args.scores)
print(f"average {value:.{args.decimals}f} ({grade(value)})")
if __name__ == "__main__":
main()
argparse turns the command line into an object with typed attributes, and generates --help and error messages for free. Positional arguments are required; --options have defaults. Passing argv explicitly, as main allows, makes the entry point easy to test without a terminal:
import subprocess
import sys
run = subprocess.run(
[sys.executable, "-m", "reports", "72", "85", "91", "--decimals", "2"],
capture_output=True, text=True,
)
print(run.stdout.strip()) # average 82.67 (pass)
bad = subprocess.run([sys.executable, "-m", "reports", "x"], capture_output=True, text=True)
print(bad.returncode, bad.stderr.splitlines()[-1])
# 2 reports: error: argument scores: invalid float value: 'x'
To share the package with others, you describe it in a pyproject.toml file (name, version, dependencies, and a [project.scripts] entry such as reports = "reports.__main__:main" that installs a reports command). Tools like uv or pip build and install it from there.
Avoid circular imports
If module a imports b and b imports a, one of them will see the other only half-initialized, and you get an ImportError mentioning a “partially initialized module”. Moving an import inside a function hides the symptom. The cleaner fix is structural: move the shared pieces into a third, lower-level module that both import. A module structure where dependencies only point “down” (handlers use services, services use models) rarely has cycles.
Bytecode caches and lazy imports
Before running a module, CPython compiles it to bytecode. For imported modules it caches the result in __pycache__/ folders, keyed by interpreter version, and recompiles only when the source changes. This saves start-up time on later runs; it does not make your functions run faster. Keep __pycache__ out of version control.
Python 3.15 adds explicit lazy imports: lazy import json binds the name immediately but loads the module only on first use. Large command-line tools with many rarely used dependencies benefit most. The trade-off is that import errors and import-time side effects move from start-up to the first use, so reach for it after measuring a slow start, not by default.
Measure before optimizing
Guesses about performance are often wrong, so measure. For a small piece of code, timeit runs it many times and reports the time:
import timeit
values = list(range(1_000))
def with_loop():
out = []
for v in values:
out.append(v * v)
return out
def with_comprehension():
return [v * v for v in values]
assert with_loop() == with_comprehension()
for func in (with_loop, with_comprehension):
best = min(timeit.repeat(func, number=1_000, repeat=5)) / 1_000
print(f"{func.__name__:<20} {best * 1e6:.1f} µs per call")
The assert first checks that both versions produce the same result; a faster function that returns something different is not an optimization. repeat runs five rounds of 1,000 calls, and taking the minimum filters out noise from other programs. Your numbers will differ from anyone else’s, so compare versions on the same machine and report the Python version with them.
For a whole program, profile instead of guessing. python -m cProfile -s cumulative script.py counts every function call and shows where the time goes. Python 3.15 also includes a sampling profiler, python -m profiling.sampling, which can attach to a running process with very little overhead. Typically the slow part is an algorithm, a database query or a network call, not the choice between a loop and a comprehension.
Practice
Add a --min option to the reports command that drops scores below a given value before averaging, and make it print no scores left and exit with status 1 if nothing remains. Then time sum(v * v for v in values) against sum([v * v for v in values]).
Answer check: python -m reports 40 80 90 --min 50 prints average 85.0 (pass). For the error case, parser.error(...) exits with status 2; use sys.exit("no scores left") for status 1. Both sum versions are close; report the numbers with your machine and Python version rather than declaring a winner.
Summary
A module runs once on first import and is cached; keep its top-level code to definitions. Packages group modules, re-export a public interface from __init__.py, and run with python -m. Guard entry points with __name__ == "__main__", parse arguments with argparse, break import cycles with a lower-level module, and measure with timeit and a profiler before optimizing.