Platform Engineering · Lesson 35

Python Functions, Modules, and Packaging

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

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

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.

Try it: what does the default list hold?

Call tag(host) several times, with the default written as a list or as None. See what the tenth host gets.

3tags on the latest host
yesone list shared by all calls

Leaking: the default list keeps every earlier call's tags

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

Structuring Python grows in four levels: functions, modules, environments and dependencies, and distribution.

Basic — Write functions

At the basic level you turn repeated code into functions.

  • def name(params):, a docstring, return.
  • Positional and keyword arguments, defaults, None for optional values.
  • Lambda for tiny throwaway functions: 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.

Intermediate — Modules and imports

At the intermediate level code is split into importable modules.

  • A package folder with __init__.py; relative imports inside it.
  • The __main__ guard; python3 -m package.module to run a module.
  • Never shadow standard modules with your file names.

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.

Advanced — Environments and dependencies

At the advanced level installs are reproducible.

  • python3 -m venv, pipx for tools, never sudo pip.
  • Lock files with hashes (pip-tools, uv, Poetry); ranges for libraries, pins for applications.
  • Dependabot or Renovate to propose upgrades with tests.

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.

Master — Distribution

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.
  • Semantic versioning and a changelog; supported Python versions tested in CI.

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 .

Go deeper

The same tool as a small package. Create the files, then install it into a venv.

diskcheck/core.py

"""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

# 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())

pyproject.toml

[project]
name = "diskcheck"
version = "0.1.0"
requires-python = ">=3.10"
dependencies = []
[project.scripts]
diskcheck = "diskcheck.cli:main"

Install and run

python3 -m venv .venv && . .venv/bin/activate
touch diskcheck/__init__.py && pip install -e . && diskcheck; echo "exit $?"

One time it broke

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.

Timeline

  • FridayAn automation tool with requirements.txt listing only package names passes CI and is released.
  • SundayA dependency publishes a new major version that removes a deprecated function the tool calls.
  • MondayThe image is rebuilt for an unrelated base update. pip installs the new major version; the tool fails on its first run. Rolled back to Friday's image, then dependencies are pinned.

What changed after

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.

Try it yourself, from scratch

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.

1. Linux commands

Type each one, read what it prints, and compare it with the note above it.

  1. 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
  2. Freeze exact versions for anything you deploy.

    /tmp/pkg-lab/bin/pip install -q "packaging==24.2" && /tmp/pkg-lab/bin/pip freeze
  3. 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
  4. Where Python looks for imports, in order.

    python3 -c "import sys; print('\n'.join(sys.path[:4]))"; rm -rf /tmp/pkg-lab

2. Python: defaults.py

This 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'],)

3. What to notice

4. Advanced: every step as one Bash script

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

5. Learn the basics behind it

New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.

If you remember nothing else

Design exercise

Turn three copy-pasted admin scripts (disk check, certificate expiry, stale users) into one installable tool with subcommands.

Clarifying questions to ask

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?

Rough sizing

Say five admins, 200 servers, and a release about once a month.

Shape of the answer

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.

Trade-offs to name

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.

Saved on this device, in this browser.
Next in this series · Lesson 36
Python Classes, Dataclasses, and Protocols

When a script starts passing around dicts with the same six keys, it is time for a class: a type that bundles data with the functions that work on it.

Go to Lesson 36 →

Or browse the full course from the Lessons index.