A script becomes a tool when its logic lives in functions with clear inputs and outputs, those functions live in modules other code can import, and the whole thing installs into a virtual environment with pinned dependencies and a command-line entry point. This lesson grows one helper from a pasted snippet into an installable command, and shows the two packaging-era bugs: a mutable default argument that leaks state between calls, and an unpinned dependency that breaks a release a week after it was tested.
Difficulty: Intermediate · Know this first: Lesson 34, Lesson 30
This bar adds up developer minutes to ship the tool and keep it working. It is a worked example, not a measurement. The parameters and pinning hops hold the bugs that pass every first test.
Call tag(host) several times, with the default written as a list or as None. See what the tenth host gets.
Leaking: the default list keeps every earlier call's tags
Three questions. No score is saved anywhere — this is just you against the material.
Structuring Python grows in four levels: functions, modules, environments and dependencies, and distribution.
At the basic level you turn repeated code into functions.
def name(params):, a docstring, return.None for optional values.sorted(rows, key=lambda r: r["pct"]).Where it breaks: forgetting return, so the caller gets None.
Try it: Basic
A function computes a value but the caller gets None. What is missing?
Now do it: Find a function in one of your scripts that prints instead of returning, and change it.
At the intermediate level code is split into importable modules.
__init__.py; relative imports inside it.__main__ guard; python3 -m package.module to run a module.Try it: Intermediate
Your script imports json and fails with "module json has no attribute loads". What is the likely cause?
Now do it: Run python3 -c "import json; print(json.__file__)" in your project folder.
At the advanced level installs are reproducible.
python3 -m venv, pipx for tools, never sudo pip.Try it: Advanced
Should a library you publish for others pin requests==2.32.3 exactly?
Now do it: Read the dependencies of one library you use in its pyproject.toml.
At the master level tools are packaged and versioned.
pyproject.toml with metadata, [project.scripts] entry points, and a version.python3 -m build for wheels; an internal package index or container images for distribution.Trade-off: packaging a tool adds files and a release step, and removes "copy this script to the server" and the drift that comes with it.
Try it: Master
What does [project.scripts] diskcheck = "diskcheck.cli:main" do?
Now do it: Add an entry point to one of your scripts and install it with pipx install .
The same tool as a small package. Create the files, then install it into a venv.
"""Parse df output and decide alert levels."""
def parse_df(text):
"""Return {mount: percent_used} from 'df -P' output."""
usage = {}
for line in text.splitlines()[1:]:
fields = line.split()
usage[fields[5]] = int(fields[4].rstrip("%"))
return usage
def level(pct, *, warn=85, crit=95):
"""Return 'critical', 'warning', or None."""
if pct >= crit:
return "critical"
if pct >= warn:
return "warning"
return None
def tag(host, env, tags=None): # None, never []
tags = list(tags or [])
tags.append(env)
return {"host": host, "tags": tags}
# diskcheck/cli.py
import subprocess, sys
from .core import parse_df, level
def main():
out = subprocess.run(["df", "-P"], capture_output=True, text=True, check=True).stdout
alerts = [(m, p, level(p)) for m, p in parse_df(out).items() if level(p)]
for mount, pct, lvl in alerts:
print(f"{lvl:<8} {pct:>3}% {mount}")
return 1 if alerts else 0
if __name__ == "__main__":
sys.exit(main())
[project] name = "diskcheck" version = "0.1.0" requires-python = ">=3.10" dependencies = [] [project.scripts] diskcheck = "diskcheck.cli:main"
python3 -m venv .venv && . .venv/bin/activate touch diskcheck/__init__.py && pip install -e . && diskcheck; echo "exit $?"
This is a composite of a failure pattern that keeps repeating; the details are illustrative. A Friday release broke on Monday without anyone changing the code.
Deployed tools use lock files with hashes, images are rebuilt from the lock file only, and Dependabot proposes upgrades through pull requests that run the full test suite.
Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.
Before you start: A virtual environment: python3 -m venv ~/py-lab && . ~/py-lab/bin/activate.
Type each one, read what it prints, and compare it with the note above it.
A virtual environment: its own python and pip.
python3 -m venv /tmp/pkg-lab && /tmp/pkg-lab/bin/python -c "import sys; print(sys.prefix)"; /tmp/pkg-lab/bin/pip --version
Freeze exact versions for anything you deploy.
/tmp/pkg-lab/bin/pip install -q "packaging==24.2" && /tmp/pkg-lab/bin/pip freeze
A file named like a standard module hides the real one.
mkdir -p /tmp/shadow && echo "x = 1" > /tmp/shadow/json.py && cd /tmp/shadow && python3 -c "import json; print(json.__file__)"; cd - >/dev/null; rm -rf /tmp/shadow
Where Python looks for imports, in order.
python3 -c "import sys; print('\n'.join(sys.path[:4]))"; rm -rf /tmp/pkg-labdefaults.pyThis program shows the mutable default argument bug: the same function with a list default and with None, called for several hosts. Save it as defaults.py, then run it.
# defaults.py
def tag_bad(host, env, tags=[]):
tags.append(env)
return {"host": host, "tags": tags}
def tag_good(host, env, tags=None):
tags = list(tags or [])
tags.append(env)
return {"host": host, "tags": tags}
for fn in (tag_bad, tag_good):
results = [fn(h, "prod") for h in ["web1", "web2", "web3"]]
print(fn.__name__, [r["tags"] for r in results])
print("the default list of tag_bad is created once:", tag_bad.__defaults__)
Run it, and you should see this output:
$ python3 defaults.py tag_bad [['prod', 'prod', 'prod'], ['prod', 'prod', 'prod'], ['prod', 'prod', 'prod']] tag_good [['prod'], ['prod'], ['prod']] the default list of tag_bad is created once: (['prod', 'prod', 'prod'],)
The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/python-functions-modules-and-packaging && cd ~/labs/python-functions-modules-and-packaging) and save this as lab.sh.
#!/usr/bin/env bash
# The Linux steps of "Python Functions, Modules, and Packaging", as one script (save it as lab.sh).
#
# ./lab.sh run every step, in order
# ./lab.sh 2 4 run only steps 2 and 4
# ./lab.sh --list list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.
STEPS=(
'A virtual environment: its own python and pip.'
'Freeze exact versions for anything you deploy.'
'A file named like a standard module hides the real one.'
'Where Python looks for imports, in order.'
)
step_1() {
python3 -m venv /tmp/pkg-lab && /tmp/pkg-lab/bin/python -c "import sys; print(sys.prefix)"; /tmp/pkg-lab/bin/pip --version
}
step_2() {
/tmp/pkg-lab/bin/pip install -q "packaging==24.2" && /tmp/pkg-lab/bin/pip freeze
}
step_3() {
mkdir -p /tmp/shadow && echo "x = 1" > /tmp/shadow/json.py && cd /tmp/shadow && python3 -c "import json; print(json.__file__)"; cd - >/dev/null; rm -rf /tmp/shadow
}
step_4() {
python3 -c "import sys; print('\n'.join(sys.path[:4]))"; rm -rf /tmp/pkg-lab
}
# print a step that has to be run by hand, instead of running it
by_hand() {
echo " (run this one yourself: $1)"
sed 's/^/ /'
}
RESULTS=()
run_step() {
local n=$1 start=$SECONDS code
printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
"step_$n"
code=$?
RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}
summary() {
echo
echo "== summary"
local r
for r in "${RESULTS[@]}"; do echo " $r"; done
}
case "${1:-}" in
-h|--help) sed -n '2,6p' "$0"; exit 0 ;;
--list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac
[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
echo "there is no step '$n'; try --list" >&2
exit 2
fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done
Then make it executable and run it:
chmod +x lab.sh ./lab.sh --list # the steps ./lab.sh # every step, then a summary of exit codes and times ./lab.sh 2 3 # only steps 2 and 3
New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.
mkdir, rm, echo, cd, Redirection, If...Else.Turn three copy-pasted admin scripts (disk check, certificate expiry, stale users) into one installable tool with subcommands.
Which functions are shared? How is the package laid out? How do admins install it, and how are dependencies pinned? How do you release a new version?
Say five admins, 200 servers, and a release about once a month.
A package with core modules per check and a cli module using argparse subcommands; pure functions returning data, tested with pytest; pyproject.toml with a console script; a lock file with hashes; pipx install from an internal index; versions tagged in Git with a changelog.
One tool is easier to install and keep consistent than three scripts, and a bug in shared code affects every check. Pinned dependencies make releases repeatable and need deliberate upgrade work.