Skip to content

08. Modules, packages and environments — Mini-project

A factory runs four sensors. Every morning a technician opens data/sensors.csv in a spreadsheet and scrolls for odd temperatures. You replace this routine with a command-line tool.

Build sensorcheck, a package with a command-line interface. The technician types one command and gets a table per sensor: the number of readings, the missing values, the mean, the minimum, the maximum and the number of readings outside a valid range. A scheduler can run the same command every hour and raise an alarm from the exit code.

The project uses most of module 08: modules with one job each, a package with __init__.py and __main__.py, relative imports, python -m, argparse (a positional argument, options with types, choices and defaults, a repeatable option and a flag), exit codes, a pyproject.toml with an entry point, and a pinned requirements file that you check against the active virtual environment. Lock files and uv projects stay in the lesson, because they need the network.

data/sensors.csv holds 8,064 rows: 4 sensors (S1 to S4) × 2,016 readings, one every 10 minutes from 2024-05-01 to 2024-05-14.

Column Type Notes
timestamp text ISO date and time, 2024-05-01T00:00:00
sensor_id text S1, S2, S3, S4
temperature_c float 22 cells are blank
humidity_pct float 29 cells are blank
vibration_mm_s float 30 cells are blank
status text ok, warn or fail

The first rows:

data/sensors.csv
timestamp,sensor_id,temperature_c,humidity_pct,vibration_mm_s,status
2024-05-01T00:00:00,S1,20.21,57.1,2.5,ok
2024-05-01T00:00:00,S2,22.3,58.4,3.39,ok

Blank cells are missing values. Read them as None and leave them out of every statistic. The data also has temperature spikes of +9 to +18 °C and a sensor (S4) whose vibration rises in the last days: your tool must find both.

Your package must:

  1. Live in a folder sensorcheck/ with at least these modules: __init__.py (version and public names), loader.py (read the CSV), checks.py (the statistics), cli.py (argparse) and __main__.py (run with python -m sensorcheck).
  2. Use relative imports inside the package. loader.py and checks.py must not print anything or read any file on import.
  3. Accept these arguments:
    • path: positional, the CSV file, converted to Path;
    • --column: one of temperature_c, humidity_pct, vibration_mm_s, default temperature_c;
    • --sensor: one of S1 to S4; the option can repeat (--sensor S3 --sensor S4); default: all sensors;
    • --low and --high: floats, defaults 18.0 and 30.0;
    • --fail-on-alert: a flag; with it, the exit code is 1 when any reading is out of range;
    • --version: prints sensorcheck 1.0.0.
  4. Reject --low values that are not below --high, and a missing file, with parser.error() (exit code 2).
  5. Print the report below for python -m sensorcheck data/sensors.csv, exactly:
Expected output
Column temperature_c, valid range 18.0 to 30.0
sensor readings missing mean min max out of range
S1 2,016 6 22.05 18.62 38.63 7
S2 2,016 4 24.60 20.24 44.89 13
S3 2,016 6 23.53 18.56 41.66 11
S4 2,016 6 26.04 23.22 44.36 8
Alerts: 39
  1. Have a main(argv=None) that returns the exit code, so that a test can call main(["data/sensors.csv"]).
  2. Come with a pyproject.toml with the name, the version, requires-python = ">=3.12", no run-time dependencies and an entry point sensorcheck = "sensorcheck.cli:main".
  3. Come with a requirements-dev.txt that pins pytest and ruff to the course versions, and a short check that the code runs in a virtual environment whose installed versions match those pins.
  4. Survive a sensor that has only blank values in the chosen column: show n/a for its statistics instead of crashing.
  1. Create the package folder. Make sensorcheck/ in your course folder with an empty __init__.py. Check that python -c "import sensorcheck" runs with no error.

  2. Write the loader. In loader.py, write to_float(text), which returns None for a blank cell, and load_readings(path, sensors=None), which reads the file with csv.DictReader and converts the three number columns. Test it in the REPL: len(load_readings("data/sensors.csv")) is 8064.

  3. Write the statistics. In checks.py, write summarize(rows, column, low, high). Group the values by sensor, drop the None values and return one dict of statistics per sensor. dict.setdefault(key, []) creates a list for a new key and returns it.

  4. Fill __init__.py. Import load_readings and summarize with relative imports, and set __version__ = "1.0.0" and __all__.

  5. Write the parser. In cli.py, write build_parser(). Use choices for --column and --sensor, action="append" for the repeatable --sensor, type=float for the limits and action="store_true" for the flag. Test it with build_parser().parse_args(["data/sensors.csv", "--sensor", "S3"]).

  6. Write the report and main(). format_summary() returns lines; main(argv=None) parses, checks the limits and the file, loads, summarizes, prints and returns 0 or 1.

  7. Add __main__.py. Two lines: import main and raise SystemExit(main()).

  8. Run it. python -m sensorcheck data/sensors.csv must print the expected report. Then try --help, a vibration check and a bad range.

  9. Write pyproject.toml next to the package folder.

  10. Pin the developer tools. Write requirements-dev.txt with pytest==9.2.0 and ruff==0.17.4. Compare each pin with importlib.metadata.version() and check sys.prefix != sys.base_prefix.

Criterion Points Full points when
Package layout 2 Five modules with one job each; python -m sensorcheck runs
Imports 2 Relative imports inside the package; no side effects on import
Arguments 3 Positional path; --column and --sensor with choices; typed limits with defaults; a working flag
Validation 2 A bad range and a missing file stop with a clear message and exit code 2
Correct report 3 The default report equals the expected output; an all-blank sensor shows n/a
Exit codes 2 main() returns 0, or 1 with --fail-on-alert and alerts
Testability 1 main(argv) and build_parser() work with argument lists
pyproject.toml 1 Valid TOML with name, version, Python version and entry point
Environment 1 requirements-dev.txt pins both tools; the check confirms the venv and the versions
Total 17 14 or more: you are ready for module 09
  1. Add --format csv, which prints the summary as CSV with csv.writer and sys.stdout, so the output can go into a spreadsheet.
  2. Add --status warn, which counts the rows with that status per sensor instead of a numeric column.
  3. Add a subcommand layout (sensorcheck summary ..., sensorcheck spikes ...) as in exercise M08-X01. spikes lists the timestamps of out-of-range readings.
  4. Install the project in editable mode (uv pip install -e ., it needs the network for the build backend) and run the sensorcheck command without python -m.
  5. Read default limits per column from a TOML file, for example [limits.vibration_mm_s] high = 4.5, with tomllib. Let the command line override them.

Try the project yourself first. Then compare. Your names can differ; your report must not.

Reference solution

The five modules:

sensorcheck/__init__.py
"""sensorcheck: check the readings of data/sensors.csv against a valid range."""
from .checks import summarize
from .loader import load_readings
__version__ = "1.0.0"
__all__ = ["load_readings", "summarize"]
sensorcheck/loader.py
"""Read the sensor CSV file. Blank cells become None."""
import csv
from pathlib import Path
NUMBER_COLUMNS = ["temperature_c", "humidity_pct", "vibration_mm_s"]
def to_float(text):
"""Convert a cell to float; a blank cell is a missing value (None)."""
text = text.strip()
return float(text) if text else None
def load_readings(path, sensors=None):
"""Return the rows of a sensor CSV file, optionally for some sensors only."""
rows = []
with Path(path).open(newline="", encoding="utf-8") as file:
for row in csv.DictReader(file):
if sensors and row["sensor_id"] not in sensors:
continue
for column in NUMBER_COLUMNS:
row[column] = to_float(row[column])
rows.append(row)
return rows
sensorcheck/checks.py
"""Summarize one numeric column per sensor and count out-of-range readings."""
def summarize(rows, column, low, high):
"""Return {sensor_id: stats dict} for one column, sorted by sensor id."""
groups = {}
for row in rows:
groups.setdefault(row["sensor_id"], []).append(row[column])
summary = {}
for sensor in sorted(groups):
values = groups[sensor]
present = [v for v in values if v is not None]
summary[sensor] = {
"readings": len(values),
"missing": len(values) - len(present),
# A sensor with only blank cells has no statistics: None, not a crash.
"mean": sum(present) / len(present) if present else None,
"min": min(present, default=None),
"max": max(present, default=None),
"out_of_range": sum(1 for v in present if not low <= v <= high),
}
return summary
sensorcheck/cli.py
"""Command-line interface of sensorcheck."""
import argparse
from pathlib import Path
from . import __version__
from .checks import summarize
from .loader import NUMBER_COLUMNS, load_readings
SENSORS = ["S1", "S2", "S3", "S4"]
def build_parser():
"""Return the argument parser of the sensorcheck command."""
parser = argparse.ArgumentParser(
prog="sensorcheck",
description="Check sensor readings against a valid range.",
)
parser.add_argument("path", type=Path, help="sensor CSV file")
parser.add_argument(
"--column",
choices=NUMBER_COLUMNS,
default="temperature_c",
help="column to check (default: %(default)s)",
)
parser.add_argument(
"--sensor",
choices=SENSORS,
action="append",
help="check only this sensor; repeat for several (default: all)",
)
parser.add_argument("--low", type=float, default=18.0, help="lowest valid value")
parser.add_argument("--high", type=float, default=30.0, help="highest valid value")
parser.add_argument(
"--fail-on-alert",
action="store_true",
help="exit with code 1 if any reading is out of range",
)
parser.add_argument(
"--version", action="version", version=f"%(prog)s {__version__}"
)
return parser
def number(value, width=8):
"""Format a statistic right-aligned; None (no data) becomes n/a."""
return f"{value:>{width}.2f}" if value is not None else f"{'n/a':>{width}}"
def format_summary(summary, column, low, high):
"""Return the report lines for a summary dict."""
lines = [
f"Column {column}, valid range {low} to {high}",
f"{'sensor':<7}{'readings':>9}{'missing':>8}{'mean':>8}"
f"{'min':>8}{'max':>8}{'out of range':>14}",
]
for sensor, s in summary.items():
lines.append(
f"{sensor:<7}{s['readings']:>9,}{s['missing']:>8}{number(s['mean'])}"
f"{number(s['min'])}{number(s['max'])}{s['out_of_range']:>14}"
)
return lines
def main(argv=None):
"""Run the check and return the exit code."""
parser = build_parser()
args = parser.parse_args(argv)
if args.low >= args.high:
parser.error(f"--low ({args.low}) must be below --high ({args.high})")
if not args.path.is_file():
parser.error(f"file not found: {args.path}")
rows = load_readings(args.path, sensors=args.sensor)
summary = summarize(rows, args.column, args.low, args.high)
for line in format_summary(summary, args.column, args.low, args.high):
print(line)
alerts = sum(s["out_of_range"] for s in summary.values())
print(f"Alerts: {alerts}")
return 1 if args.fail_on_alert and alerts else 0
sensorcheck/__main__.py
"""Run the package as a program: python -m sensorcheck ..."""
from .cli import main
raise SystemExit(main())

The project file, next to the sensorcheck/ folder:

pyproject.toml
[project]
name = "sensorcheck"
version = "1.0.0"
description = "Check sensor readings against a valid range."
requires-python = ">=3.12"
dependencies = []
[project.scripts]
sensorcheck = "sensorcheck.cli:main"
[build-system]
requires = ["hatchling>=1.27"]
build-backend = "hatchling.build"

The pinned developer tools, also next to the package folder:

requirements-dev.txt
# requirements-dev.txt: developer tools for sensorcheck, pinned to the course versions.
# Install: uv pip install -r requirements-dev.txt
pytest==9.2.0
ruff==0.17.4

Check the environment before you work on the project:

import sys
from importlib.metadata import version
from pathlib import Path
with open("requirements-dev.txt", encoding="utf-8") as file:
lines = [line.strip() for line in file if line.strip() and not line.startswith("#")]
print("Virtual environment:", Path(sys.prefix).name, sys.prefix != sys.base_prefix)
for line in lines:
name, wanted = line.split("==")
installed = version(name)
print(f"{name:<7} wanted {wanted:<7} installed {installed:<7}", installed == wanted)
assert installed == wanted
Output
Virtual environment: .venv True
pytest wanted 9.2.0 installed 9.2.0 True
ruff wanted 0.17.4 installed 0.17.4 True

Run the default check:

Terminal
python -m sensorcheck data/sensors.csv
Output
Column temperature_c, valid range 18.0 to 30.0
sensor readings missing mean min max out of range
S1 2,016 6 22.05 18.62 38.63 7
S2 2,016 4 24.60 20.24 44.89 13
S3 2,016 6 23.53 18.56 41.66 11
S4 2,016 6 26.04 23.22 44.36 8
Alerts: 39

Check the vibration of S3 and S4 with a stricter limit, and read the exit code. The \ at the end of a line continues the command on the next line (in PowerShell, write the command on one line):

Terminal
python -m sensorcheck data/sensors.csv --column vibration_mm_s \
--low 0 --high 4.5 --sensor S3 --sensor S4 --fail-on-alert
echo "exit code: $?"
Output
Column vibration_mm_s, valid range 0.0 to 4.5
sensor readings missing mean min max out of range
S3 2,016 10 1.96 1.15 9.99 13
S4 2,016 7 4.02 1.92 18.98 410
Alerts: 423
exit code: 1

The help text and the errors:

Terminal
python -m sensorcheck --help
python -m sensorcheck data/sensors.csv --low 30 --high 20 2>&1 | tail -n 1
python -m sensorcheck --version
Output
usage: sensorcheck [-h] [--column {temperature_c,humidity_pct,vibration_mm_s}]
[--sensor {S1,S2,S3,S4}] [--low LOW] [--high HIGH] [--fail-on-alert]
[--version]
path
Check sensor readings against a valid range.
positional arguments:
path sensor CSV file
options:
-h, --help show this help message and exit
--column {temperature_c,humidity_pct,vibration_mm_s}
column to check (default: temperature_c)
--sensor {S1,S2,S3,S4}
check only this sensor; repeat for several (default: all)
--low LOW lowest valid value
--high HIGH highest valid value
--fail-on-alert exit with code 1 if any reading is out of range
--version show program's version number and exit
sensorcheck: error: --low (30.0) must be below --high (20.0)
sensorcheck 1.0.0

Test main() and the parser from Python:

from sensorcheck import load_readings, summarize
from sensorcheck.cli import build_parser, format_summary, main
argv = ["data/sensors.csv", "--sensor", "S4", "--sensor", "S1"]
args = build_parser().parse_args(argv)
print(args.sensor, args.column, args.low, args.high, args.fail_on_alert)
rows = load_readings("data/sensors.csv", sensors=["S4"])
print(len(rows), summarize(rows, "humidity_pct", 40, 70)["S4"]["out_of_range"])
code = main(["data/sensors.csv", "--sensor", "S2", "--fail-on-alert"])
print("exit code:", code)
assert code == 1
assert main(["data/sensors.csv", "--sensor", "S2", "--high", "50"]) == 0
blank = [{"sensor_id": "S9", "temperature_c": None}] * 3 # a sensor with no data
empty = summarize(blank, "temperature_c", 18, 30)
print(empty["S9"])
print(format_summary(empty, "temperature_c", 18, 30)[-1])
assert empty["S9"]["mean"] is None
Output
['S4', 'S1'] temperature_c 18.0 30.0 False
2016 0
Column temperature_c, valid range 18.0 to 30.0
sensor readings missing mean min max out of range
S2 2,016 4 24.60 20.24 44.89 13
Alerts: 13
exit code: 1
Column temperature_c, valid range 18.0 to 50.0
sensor readings missing mean min max out of range
S2 2,016 4 24.60 20.24 44.89 0
Alerts: 0
{'readings': 3, 'missing': 3, 'mean': None, 'min': None, 'max': None, 'out_of_range': 0}
S9 3 3 n/a n/a n/a 0

How it works:

  1. One job per module. loader.py knows the file format, checks.py knows the statistics, cli.py knows the command line. You can test summarize() with three hand-made rows and no file.
  2. Missing values. to_float() turns a blank cell into None. summarize() counts the None values as missing and computes the statistics on the rest, so a gap never becomes a fake 0 °C.
  3. The repeatable option. action="append" collects every --sensor value in a list (['S4', 'S1']). Without the option, the value is None, and load_readings() keeps every sensor.
  4. Validation. choices rejects an unknown sensor or column before any work starts. parser.error() covers the rules that involve two arguments (--low below --high) and the file check.
  5. Exit codes. main() returns 1 only when the flag is set and alerts exist. __main__.py passes the value to SystemExit, so echo $? and schedulers see it. The vibration check finds 410 readings above 4.5 mm/s for S4: the wear that starts on May 12.
  6. Testability. main(argv) takes a list, so the last block runs the whole tool twice inside Python, with no terminal. The humidity check of S4 finds no reading outside 40 to 70 %.
  7. A sensor with no data. The hand-made sensor S9 has only blank cells. summarize() gives None for its mean, minimum and maximum (min(present, default=None) avoids the ValueError of an empty list), and format_summary() prints them as n/a. Without the guard, the mean would raise ZeroDivisionError.
  8. Environment check. The pins in requirements-dev.txt match the installed versions, and sys.prefix shows that the code runs in .venv. If a line printed False, uv pip sync requirements-dev.txt would fix the environment.

Alternative: pandas does the statistics in a few lines (df.groupby("sensor_id")["temperature_c"].agg(["count", "mean", "min", "max"]), module 25). The package structure, the CLI and the exit codes stay the same; only loader.py and checks.py change. That is the benefit of one job per module.