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.
Dataset
Section titled “Dataset”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:
timestamp,sensor_id,temperature_c,humidity_pct,vibration_mm_s,status2024-05-01T00:00:00,S1,20.21,57.1,2.5,ok2024-05-01T00:00:00,S2,22.3,58.4,3.39,okBlank 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.
Requirements
Section titled “Requirements”Your package must:
- 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 withpython -m sensorcheck). - Use relative imports inside the package.
loader.pyandchecks.pymust not print anything or read any file on import. - Accept these arguments:
path: positional, the CSV file, converted toPath;--column: one oftemperature_c,humidity_pct,vibration_mm_s, defaulttemperature_c;--sensor: one ofS1toS4; the option can repeat (--sensor S3 --sensor S4); default: all sensors;--lowand--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: printssensorcheck 1.0.0.
- Reject
--lowvalues that are not below--high, and a missing file, withparser.error()(exit code 2). - Print the report below for
python -m sensorcheck data/sensors.csv, exactly:
Column temperature_c, valid range 18.0 to 30.0sensor readings missing mean min max out of rangeS1 2,016 6 22.05 18.62 38.63 7S2 2,016 4 24.60 20.24 44.89 13S3 2,016 6 23.53 18.56 41.66 11S4 2,016 6 26.04 23.22 44.36 8Alerts: 39- Have a
main(argv=None)that returns the exit code, so that a test can callmain(["data/sensors.csv"]). - Come with a
pyproject.tomlwith the name, the version,requires-python = ">=3.12", no run-time dependencies and an entry pointsensorcheck = "sensorcheck.cli:main". - Come with a
requirements-dev.txtthat 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. - Survive a sensor that has only blank values in the chosen column: show
n/afor its statistics instead of crashing.
Step plan
Section titled “Step plan”-
Create the package folder. Make
sensorcheck/in your course folder with an empty__init__.py. Check thatpython -c "import sensorcheck"runs with no error. -
Write the loader. In
loader.py, writeto_float(text), which returnsNonefor a blank cell, andload_readings(path, sensors=None), which reads the file withcsv.DictReaderand converts the three number columns. Test it in the REPL:len(load_readings("data/sensors.csv"))is 8064. -
Write the statistics. In
checks.py, writesummarize(rows, column, low, high). Group the values by sensor, drop theNonevalues and return one dict of statistics per sensor.dict.setdefault(key, [])creates a list for a new key and returns it. -
Fill
__init__.py. Importload_readingsandsummarizewith relative imports, and set__version__ = "1.0.0"and__all__. -
Write the parser. In
cli.py, writebuild_parser(). Usechoicesfor--columnand--sensor,action="append"for the repeatable--sensor,type=floatfor the limits andaction="store_true"for the flag. Test it withbuild_parser().parse_args(["data/sensors.csv", "--sensor", "S3"]). -
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. -
Add
__main__.py. Two lines: importmainandraise SystemExit(main()). -
Run it.
python -m sensorcheck data/sensors.csvmust print the expected report. Then try--help, a vibration check and a bad range. -
Write
pyproject.tomlnext to the package folder. -
Pin the developer tools. Write
requirements-dev.txtwithpytest==9.2.0andruff==0.17.4. Compare each pin withimportlib.metadata.version()and checksys.prefix != sys.base_prefix.
Rubric
Section titled “Rubric”| 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 |
Stretch goals
Section titled “Stretch goals”- Add
--format csv, which prints the summary as CSV withcsv.writerandsys.stdout, so the output can go into a spreadsheet. - Add
--status warn, which counts the rows with that status per sensor instead of a numeric column. - Add a subcommand layout (
sensorcheck summary ...,sensorcheck spikes ...) as in exercise M08-X01.spikeslists the timestamps of out-of-range readings. - Install the project in editable mode (
uv pip install -e ., it needs the network for the build backend) and run thesensorcheckcommand withoutpython -m. - Read default limits per column from a TOML file, for example
[limits.vibration_mm_s] high = 4.5, withtomllib. Let the command line override them.
Reference solution
Section titled “Reference solution”Try the project yourself first. Then compare. Your names can differ; your report must not.
Reference solution
The five modules:
"""sensorcheck: check the readings of data/sensors.csv against a valid range."""
from .checks import summarizefrom .loader import load_readings
__version__ = "1.0.0"__all__ = ["load_readings", "summarize"]"""Read the sensor CSV file. Blank cells become None."""
import csvfrom 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"""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"""Command-line interface of sensorcheck."""
import argparsefrom pathlib import Path
from . import __version__from .checks import summarizefrom .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"""Run the package as a program: python -m sensorcheck ..."""
from .cli import main
raise SystemExit(main())The project file, next to the sensorcheck/ folder:
[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: developer tools for sensorcheck, pinned to the course versions.# Install: uv pip install -r requirements-dev.txtpytest==9.2.0ruff==0.17.4Check the environment before you work on the project:
import sysfrom importlib.metadata import versionfrom 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 == wantedVirtual environment: .venv Truepytest wanted 9.2.0 installed 9.2.0 Trueruff wanted 0.17.4 installed 0.17.4 TrueRun the default check:
python -m sensorcheck data/sensors.csvColumn temperature_c, valid range 18.0 to 30.0sensor readings missing mean min max out of rangeS1 2,016 6 22.05 18.62 38.63 7S2 2,016 4 24.60 20.24 44.89 13S3 2,016 6 23.53 18.56 41.66 11S4 2,016 6 26.04 23.22 44.36 8Alerts: 39Check 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):
python -m sensorcheck data/sensors.csv --column vibration_mm_s \ --low 0 --high 4.5 --sensor S3 --sensor S4 --fail-on-alertecho "exit code: $?"Column vibration_mm_s, valid range 0.0 to 4.5sensor readings missing mean min max out of rangeS3 2,016 10 1.96 1.15 9.99 13S4 2,016 7 4.02 1.92 18.98 410Alerts: 423exit code: 1The help text and the errors:
python -m sensorcheck --helppython -m sensorcheck data/sensors.csv --low 30 --high 20 2>&1 | tail -n 1python -m sensorcheck --versionusage: 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 exitsensorcheck: error: --low (30.0) must be below --high (20.0)sensorcheck 1.0.0Test main() and the parser from Python:
from sensorcheck import load_readings, summarizefrom 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 == 1assert main(["data/sensors.csv", "--sensor", "S2", "--high", "50"]) == 0
blank = [{"sensor_id": "S9", "temperature_c": None}] * 3 # a sensor with no dataempty = summarize(blank, "temperature_c", 18, 30)print(empty["S9"])print(format_summary(empty, "temperature_c", 18, 30)[-1])assert empty["S9"]["mean"] is None['S4', 'S1'] temperature_c 18.0 30.0 False2016 0Column temperature_c, valid range 18.0 to 30.0sensor readings missing mean min max out of rangeS2 2,016 4 24.60 20.24 44.89 13Alerts: 13exit code: 1Column temperature_c, valid range 18.0 to 50.0sensor readings missing mean min max out of rangeS2 2,016 4 24.60 20.24 44.89 0Alerts: 0{'readings': 3, 'missing': 3, 'mean': None, 'min': None, 'max': None, 'out_of_range': 0}S9 3 3 n/a n/a n/a 0How it works:
- One job per module.
loader.pyknows the file format,checks.pyknows the statistics,cli.pyknows the command line. You can testsummarize()with three hand-made rows and no file. - Missing values.
to_float()turns a blank cell intoNone.summarize()counts theNonevalues as missing and computes the statistics on the rest, so a gap never becomes a fake 0 °C. - The repeatable option.
action="append"collects every--sensorvalue in a list (['S4', 'S1']). Without the option, the value isNone, andload_readings()keeps every sensor. - Validation.
choicesrejects an unknown sensor or column before any work starts.parser.error()covers the rules that involve two arguments (--lowbelow--high) and the file check. - Exit codes.
main()returns 1 only when the flag is set and alerts exist.__main__.pypasses the value toSystemExit, soecho $?and schedulers see it. The vibration check finds 410 readings above 4.5 mm/s for S4: the wear that starts on May 12. - 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 %. - A sensor with no data. The hand-made sensor S9 has only blank cells.
summarize()givesNonefor its mean, minimum and maximum (min(present, default=None)avoids theValueErrorof an empty list), andformat_summary()prints them asn/a. Without the guard, the mean would raiseZeroDivisionError. - Environment check. The pins in
requirements-dev.txtmatch the installed versions, andsys.prefixshows that the code runs in.venv. If a line printedFalse,uv pip sync requirements-dev.txtwould 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.