Why code is split into modules and packages
2 min readIn the previous lesson you wrote scripts and functions inside one file. That works until the file grows to hundreds of lines, or until a second script needs the same function. Copying the function into two places is the trap to avoid: the two copies drift apart, a bug is fixed in one and not the other, and now you maintain the same logic twice.
Python's answer has three levels. A a single .py file that Python can execute and import, whose top-level names form its own namespace is one file, and you already use modules without noticing: every .py file is a module. A a directory that groups modules and subpackages under one dotted name, so related code ships and imports together is a directory of modules. And an the statement that loads a module or package, executes its top-level code once, and binds its namespace to a name in your program statement is the door into both.
The dotted name is the map. In devkit.flash, devkit is a package and flash is a module inside it. In devkit.util.crc, util is a subpackage and crc a module inside that. Dots mean "inside", and they let a hundred modules live in one place without their names colliding.
For embedded tooling this is not a nicety, it is the difference between a folder of disposable scripts and a toolbox. A team building SensorNode boards ends up with the same pieces in every script: a function to find the USB serial port, a function to parse a boot log, a function to flash an image. Put those in a package, install it once, and every script imports them instead of pasting them. The package becomes the one place where the flashing logic lives, so a fix to it reaches every tool that uses it.
The import statement and the module search order
4 min readThere are several import forms, and each binds a different name.
import devkit.flash # binds the name devkit, not devkit.flash
from devkit.flash import write_image # binds write_image directly
from devkit import flash # binds flash
import devkit.flash as f # binds the alias f
from devkit.flash import * # imports public names, see the next section
Note the first form carefully: import devkit.flash binds devkit, so you call devkit.flash.write_image(...). To reach the module with its short name you write from devkit import flash. All of these execute the module's top-level code exactly once, no matter which form you use or how many times you import it.
When you run an import, Python follows a fixed sequence. It first checks the the list of directory and archive paths that Python searches, in order, to find a module named in an import cache, then the built-in modules, then walks the directories in sys.path. This is the search order, and it is the first place to look when an import fails or resolves to the wrong file.
python3 -c "import sys; print(sys.path)"
# typical output: ['', '/usr/lib/python312.zip', '/usr/lib/python3.12',
# '/usr/lib/python3.12/lib-dynload', '/home/learner/.local/lib/python3.12/site-packages',
# '/usr/local/lib/python3.12/dist-packages', '/usr/lib/python3/dist-packages']
The output above is typical for Ubuntu 24.04; yours will differ in the exact paths. The important fact is the first entry. When you run python3 tool.py, sys.path[0] is the directory that contains tool.py. When you run python3 -m devkit or work in the interactive prompt, sys.path[0] is the empty string, which means the current working directory. This single difference decides whether import devkit finds the copy in your project or the copy installed in site-packages, and it is behind the classic "it imports the wrong version" bug.
The import system also caches. The first time a module is imported, Python executes its top-level code and stores the module object in sys.modules, a dictionary keyed by module name. Every later import of the same name returns the cached object without re-executing the code. That is why a module's top-level statements run only once, and why editing a module and importing it again in the same process does not reload it.
Check sys.modules: if the name is already imported, return the cached module object.
Check built-ins: a small set such as sys and builtins is searched before any file.
Walk sys.path in order: each directory and zip archive is searched for a match.
Find a file or package: a
.pyfile, a directory with__init__.py, or a compiled extension.Execute and cache: run the top-level code, put the module in sys.modules, bind the name.
Going deeperInside the finders and loaders
The import machinery is not one loop but a chain of finders held in sys.meta_path. The two you always meet are BuiltinImporter, which serves the built-in modules, and PathFinder, which walks sys.path. A finder returns a spec, and a loader executes the code from that spec. When PathFinder meets a directory it delegates to a FileFinder that knows the extensions: it can load a source file, a cached bytecode file, or a compiled extension module such as a .so on Linux or a .pyd on Windows. This is why a C extension and a pure-Python module are imported with the same import statement, and why zipimport can import straight from a .zip on sys.path. The bytecode cache you saw in the previous lesson, __pycache__/*.pyc, is how FileFinder skips recompiling a module whose source has not changed. If an import fails, the error message tells you the chain it walked: ModuleNotFoundError: No module named 'devkit' means the name was in neither sys.modules, the built-ins, nor any directory on sys.path.
Packages, __init__.py, and the public API
4 min readA regular package is a directory containing an __init__.py file. The file can be empty, and for the smallest packages that is enough: the folder is now importable, and its submodules are reached by dotted name. But __init__.py is also code, and it runs once, when the package is first imported. That makes it the natural place to set up the package's public face.
A a package with no init.py, whose portions can live in several directories on sys.path and merge into one dotted name is the alternative. Because it has no __init__.py, it has no code of its own and no single directory; it simply merges every directory named devkit that appears on sys.path. Namespace packages matter when you deliberately want one package name to be assembled from several projects, which is how plugin systems let other packages drop new subpackages into your namespace. For the normal case, one team and one repository, write the __init__.py and keep the regular package.
The two import styles inside a package are worth separating early. An absolute import names the full path from the top: import devkit.serial or from devkit.serial import open_port. A relative import starts with a dot and is resolved against the current module: from . import serial (a sibling module), from .serial import open_port, or from .. import util (one level up). Relative imports only work when the module knows it is inside a package, a fact that becomes important in the next section.
__init__.py lets you control the public surface. Suppose the team wants callers to write from devkit import write_image rather than from devkit.flash import write_image. You re-export the name:
# devkit/__init__.py
"""Flash, provision and test tooling for SensorNode boards."""
from .flash import write_image
from .serial import open_port
__all__ = ["write_image", "open_port"]
The __all__ list does two jobs. It is the list of names that from devkit import * imports, and it doubles as documentation of the package's intended public API. Everything not listed is still reachable by its full dotted name, but __all__ tells a reader and a linter which names are the stable contract.
When a package grows past a few modules, the __init__.py should stay thin. Its job is to re-export a small number of names and set __all__, not to contain logic. Keep the real code in leaf modules, keep each module importing its siblings with relative imports (from . import serial), and re-export only what callers should rely on. Inside the package, modules may import each other freely by relative name; outside the package, callers should reach in through the public names in __init__.py. A subpackage is just a nested directory with its own __init__.py, and the same rules apply at each level. This keeps the dependency direction one-way and makes the package cheap to test, because each leaf module can be imported on its own. The failure mode this avoids is a tangle where every module imports every other, so nothing can be tested or reused in isolation.
Scripts versus importable code: __main__ and python -m
2 min readThe previous lesson introduced the if __name__ == "__main__" guard. Here is why it is a design rule, not a convention. When you run python3 devkit.py, Python sets the module's __name__ to the string "__main__". When some other code does import devkit, __name__ is set to "devkit". The guard runs the block only in the first case:
def main() -> int:
...
if __name__ == "__main__":
sys.exit(main())
The point is not the guard itself, it is the side effects it fences off. Any statement at module level runs at import time: a print, a network call, opening a serial port, writing a file. If devkit/flash.py opens the serial port at the top of the file, then importing devkit.flash to reuse one function also opens the port. That is why side effects belong inside functions, and why the only module-level code in a well-behaved tool is definitions, constants, and the one guarded call to main.
The second half is python -m. A file inside a package can be run in two ways, and they are not the same:
python3 devkit/cli.py # runs the file; the module has no package context
python3 -m devkit.cli # runs the same code with package context set
The difference shows up in relative imports. When you run the file directly, Python treats it as a top-level script: its package context is empty, so a relative import inside it fails with ImportError: attempted relative import with no known parent package. Running python -m devkit.cli sets the module's __package__ to "devkit", so from .flash import write_image resolves. The -m form is the correct way to run a module that lives inside a package.
A package can also run itself. If devkit/__main__.py exists, then python3 -m devkit executes it. That file is where a package that is also a command puts its entry logic, and it is the same mechanism a console script will reuse later in this lesson.
Project layout: src layout versus flat layout
2 min readA repository has to hold the package, the tests, the documentation, and the build files. Two layouts are common, and they differ in one respect: where the importable package directory lives.
The flat layout puts the package at the top of the repository, next to everything else:
devkit-project/
devkit/
__init__.py
flash.py
tests/
test_flash.py
pyproject.toml
README.md
The src layout hides the package one level down, under a src directory:
devkit-project/
src/
devkit/
__init__.py
flash.py
tests/
test_flash.py
pyproject.toml
README.md
The difference is what import devkit finds when you run the tests from the repository root. With the flat layout, the package directory is the current directory, and because the current directory is on sys.path, the tests import the source tree directly. That sounds convenient but it is a trap: it means the package imports successfully even if your pyproject.toml is broken and nothing would install. The tests pass against code that could never be shipped. With the src layout, the source is not importable from the root, so you must install the package, at least in editable mode, before the tests can import it. The tests then run against the installed artifact, the same one a user gets.
The rule that falls out of this: use the src layout for any package you intend to install and distribute, and accept the flat layout only for a self-contained application that is never imported by anything else. The other files have fixed homes in both layouts: tests in tests/, documentation in docs/, and configuration in pyproject.toml at the root, with README.md and a licence file beside it. A .gitignore excludes dist/, *.egg-info/, and the virtual environment.
pyproject.toml: metadata, build backends, and entry points
4 min readThe pyproject.toml file is a TOML file at the repository root that is now the single source of truth for a Python project. Historically a project was described by setup.py, a Python script with real code that ran at build time. That was replaced in two steps: PEP 518 made pyproject.toml the place to declare build requirements, and PEP 621 standardised the project metadata that had lived in setup.py. Here is a complete small example:
[build-system]
requires = ["setuptools>=68"]
build-backend = "setuptools.build_meta"
[project]
name = "devkit"
version = "0.1.0"
description = "Flash, provision and test SensorNode boards"
readme = "README.md"
requires-python = ">=3.11"
dependencies = [
"pyserial>=3.5",
"rich>=13.0",
]
[project.optional-dependencies]
dev = ["pytest>=8", "build>=1"]
[project.scripts]
devkit = "devkit.cli:main"
The [build-system] table names the build backend, the piece of software that actually turns the source tree into installable artifacts. build-backend is one of several interchangeable implementations: setuptools.build_meta, hatchling.build, flit_core.buildapi, or poetry.core.masonry.api. The requires line tells the build frontend what to install before it can run that backend. This decoupling, the subject of the next section, is the key idea: the backend builds, the frontend drives.
The [project] table is the metadata, standardised by PEP 621. name and version identify the distribution; requires-python is the floor of Python versions the package supports, written as a version specifier such as >=3.11; dependencies lists the packages the project needs at run time. Because Ubuntu 24.04 ships Python 3.12 and this program's floor is 3.11, >=3.11 is a safe, honest lower bound.
The [project.scripts] table is where a command name becomes a function. The line devkit = "devkit.cli:main" declares a a named mapping, declared in project metadata, from a command or plugin name to a specific object such as module:function. When the package is installed, pip generates a a small executable wrapper installed on PATH that imports the target function of an entry point and calls it named devkit, so typing devkit in the shell runs main inside devkit.cli. The right-hand side is always module:attribute, and the attribute must be a callable taking no arguments. You can read a pyproject.toml from Python itself with the standard-library tomllib module, added in 3.11.
The shell finds the wrapper:
devkitis an executable in the environment's bin directory, on PATH.The wrapper imports the module: it imports devkit.cli, executing its top-level code once.
The wrapper calls main: it calls the function named by the entry point, with no arguments.
main parses the arguments: argparse reads sys.argv and produces a namespace.
The command runs: the selected function does its work and returns a status code.
Going deeperThe generated wrapper and entry_points.txt
The console script you type is not your code; it is a tiny wrapper generated at install time. Installed distributions carry their metadata in a *.dist-info directory inside site-packages, and the entry points live in a file there called entry_points.txt:
[console_scripts]
devkit = devkit.cli:main
The wrapper script, in the environment's bin/ directory, is a short Python program whose shebang points at that environment's interpreter. Modern installers generate a wrapper that loads the entry point through importlib.metadata.entry_points, looks up the console_scripts group, and calls the object it names; the return value of your function becomes the process exit status. This indirection is what allows tools other than your own to discover your commands: pip, uv, and plugin systems such as pytest all read the same entry-point metadata, which is why pytest plugins are declared in a similar entry_points.txt with a different group name.
Building and installing: wheels, sdists, and editable installs
4 min readA a pre-built distribution archive, a ZIP file with a standard layout, that installs by unpacking with no build step is the thing you install. Its filename encodes what it contains: devkit-0.1.0-py3-none-any.whl is version 0.1.0, pure Python (py3), no ABI requirement (none), any platform (any). A wheel for compiled code instead carries a platform tag such as cp312-cp312-manylinux_x86_64, and the installer picks the matching one.
An a source distribution, a tar archive of the source tree plus generated metadata, from which a wheel is built later is the source, packaged for others to build. It holds the pyproject.toml, the README, and the source under src/, plus a generated PKG-INFO. A wheel is for installing; an sdist is for publishing so that a build can happen on each target platform.
1install from the source tree
pip install . # builds a wheel, installs it into the active environment
pip install -e . # editable: no copy, imports resolve to your source tree
pip install . runs a full build and installs a copy into site-packages. Editing your source afterwards does nothing until you reinstall. pip install -e . installs in editable mode: nothing is copied, and a small finder redirects import devkit to your src/devkit, so every edit is visible immediately. Editable mode is what you use while developing; a normal install is what you ship.
2build distributable artifacts
python3 -m pip install build
python3 -m build # builds both an sdist and a wheel into dist/
python3 -m build --wheel # just the wheel
python -m build runs the build backend through the frontend defined by PEP 517, and by default produces both artifacts in a dist/ directory.
3inspect what actually ships
unzip -l dist/devkit-0.1.0-py3-none-any.whl
The listing shows the package files and a devkit-0.1.0.dist-info/ directory containing METADATA, WHEEL, RECORD and entry_points.txt. This is the fastest way to catch a packaging bug: a missing src mapping, a forgotten data file, or an entry point that did not get declared.
Going deeperPEP 517 and 518: why the backend is decoupled
Before PEP 517, the only build system was setuptools, and pip talked to it through setup.py. PEP 517 defined a small interface between a build frontend and a build backend, and PEP 518 made pyproject.toml the place to declare which backend a project uses. The backend implements a handful of hooks: build_wheel, build_sdist, prepare_metadata_for_build_wheel, and get_requires_for_build_wheel. The frontend, which is pip, build, or uv, drives those hooks and never needs to know whether the backend is setuptools, hatchling, flit or poetry-core. This is why a project can switch backends without changing a single command the user types, and why pip can install a project whose build system it has never heard of: it reads [build-system].requires, installs those requirements into an isolated build environment, then calls the declared backend. The isolation matters too, because building one project must not be affected by whatever other packages happen to be installed in your environment.
Dependencies and reproducible resolution: specifiers, lock files, uv
3 min readDependencies are declared with version specifiers, the small grammar defined by PEP 440. Each one constrains a version:
pyserial==3.5 # exactly 3.5
pyserial>=3.5 # 3.5 or newer
pyserial~=3.5.2 # 3.5.2 or newer, but below 3.6.0 (compatible release)
pyserial!=3.5.1 # anything except 3.5.1
pyserial>=3.5,<4.0 # a range, combined with commas as AND
The tilde form ~=3.5.2 means "at least 3.5.2 and still compatible with it": it allows patch updates within 3.5 but not the next minor version. ~=3.5 means at least 3.5 and below 4.0. This is the most useful specifier for a library, because it pins the major and minor versions while allowing patches.
There are three places to record dependencies, and they serve different purposes. [project].dependencies in pyproject.toml declares what the package needs, usually with loose lower bounds, because a library should stay installable across many environments. A requirements.txt is a flat list that pip install -r installs, used to pin an application's environment. Neither is a lock. The reproducible answer is a a generated file that records the exact version and hash of every package in the resolved dependency graph, so a reinstall reproduces the same set.
pip freeze dumps what happens to be installed, but it does not resolve from your declared dependencies. The tools that do are pip-compile from pip-tools, which generates a fully pinned requirements.txt from a requirements.in; Poetry, whose poetry.lock pins the whole graph; and uv, whose uv.lock does the same. A lock file records exact versions and content hashes for every transitive dependency, and you commit it to the repository. A build host that installs from the lock gets exactly the set the developer tested, which is the property an embedded cross-build host depends on.
The modern tool worth knowing is uv, a fast package and project manager written in Rust that replaces pip, venv and pip-tools and reads the same pyproject.toml:
uv venv # create .venv in milliseconds
uv pip install pyserial # install into the active environment
uv add pyserial # add to pyproject.toml and the lock file
uv lock # resolve and write uv.lock
uv sync # install exactly what uv.lock pins
uv run devkit flash fw.bin # run a command in the project environment
uv reads the same pyproject.toml and the same [project.scripts] entry points, so a project that builds with setuptools or hatchling works unchanged. Its speed comes from the Rust implementation and an aggressive cache, and it has replaced the older pip-and-virtualenv workflow in many teams, including the one described in the previous lesson.
Going deeperWhat a lock file records, and why hashes matter
A lock file is more than a version list. Each entry pins a distribution name to an exact version, a set of content hashes, and often the environment markers that say which platform a package applies to. The hashes are the supply-chain protection: pip and uv verify the downloaded artifact against them, so a lock generated on a clean machine cannot be silently substituted for a malicious package with the same version number. This is why a lock file, not a hand-written requirements.txt, is the reproducible artifact. The three tools draw the line differently: pip-compile produces a flat pinned requirements.txt; poetry.lock and uv.lock keep the full dependency graph with hashes. For an embedded team, the payoff is concrete: the host that builds a Yocto or Buildroot image runs Python tools such as kas and BitBake wrappers, and pinning those tools with a lock file means the build host itself is reproducible, not just the image it produces.
argparse: a command-line tool with subcommands
4 min readThe argument for a parser is the one-liner of code it replaces. Parsing sys.argv by hand means checking --port exists, finding the next element, converting it, and repeating for every flag:
import sys
def main() -> int:
args = sys.argv[1:]
if not args:
print("usage: flash IMAGE [--port PORT]", file=sys.stderr)
return 2
image = args[0]
port = "/dev/ttyUSB0"
if "--port" in args:
port = args[args.index("--port") + 1]
...
This breaks the moment a flag is repeated, a value is missing, a value is not an integer, or the user asks for help. argparse handles all of it. A a named verb after the program, such as flash in devkit flash, that selects a distinct set of arguments and an action model is how real tools such as git and west are shaped, and argparse supports it directly.
import argparse
import sys
def flash_cmd(args: argparse.Namespace) -> int:
print(f"flashing {args.image} to {args.board}")
return 0
def serial_cmd(args: argparse.Namespace) -> int:
print(f"console on {args.port} at {args.baud}")
return 0
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
prog="devkit",
description="Flash, provision and test SensorNode boards.",
)
sub = parser.add_subparsers(dest="command", required=True)
p_flash = sub.add_parser("flash", help="write a firmware image")
p_flash.add_argument("image", help="path to the image file")
p_flash.add_argument("--board", "-b", default="sn-01", help="board to target")
p_flash.add_argument("--verify", action="store_true", help="verify after write")
p_flash.set_defaults(func=flash_cmd)
p_serial = sub.add_parser("serial", help="open a serial console")
p_serial.add_argument("--port", "-p", default="/dev/ttyUSB0")
p_serial.add_argument("--baud", type=int, default=115200,
choices=[9600, 19200, 38400, 57600, 115200])
p_serial.set_defaults(func=serial_cmd)
return parser
def main(argv: list[str] | None = None) -> int:
parser = build_parser()
args = parser.parse_args(argv)
return args.func(args)
if __name__ == "__main__":
sys.exit(main())
1build the parser
ArgumentParser holds the top-level description, which appears in the help text. The prog name defaults to sys.argv[0]; set it explicitly so the help reads devkit, not the full path.
2add arguments
Positional arguments are bare names such as image, matched in order. Optional arguments start with dashes: --board with a short alias -b. default supplies the value when the flag is absent. type=int converts the string, and a bad value makes argparse print an error and exit with status 2. choices=[...] rejects anything outside the list. action="store_true" makes --verify a flag that is False by default and True when present.
3add subcommands
add_subparsers(dest="command", required=True) records which verb was chosen. Each add_parser gets its own arguments, and set_defaults(func=flash_cmd) attaches the function to call. The required=True keyword, available since Python 3.7, makes a missing subcommand an error instead of a silent None.
4parse and dispatch
parse_args(argv) reads sys.argv[1:] when argv is None, or the list you pass in tests. It returns a Namespace whose attributes are the argument names. The dispatch args.func(args) hands the whole namespace to the selected function, so each subcommand receives only what it declared.
5rely on the help and the exit code
devkit --help and devkit flash --help print generated usage text. A missing argument, an unknown flag, or a bad type or choices value prints an error to stderr and exits with status 2, which is the convention for usage errors.
Raw argv, exit codes, and click or typer
4 min readThe raw interface is two objects in sys. sys.argv is a list of strings: sys.argv[0] is the program name and sys.argv[1:] are the arguments, all as text, never converted. sys.exit(code) raises SystemExit, which the interpreter turns into the process exit status. The convention is short: 0 means success, and any non-zero value means failure. A few codes are de facto standard, and a tool should use them deliberately rather than returning 1 for everything:
import sys
def main() -> int:
if not image_exists:
return 1 # a generic runtime failure
if not supported_board:
return 2 # misuse: bad arguments, the argparse convention
return 0 # success
if __name__ == "__main__":
sys.exit(main())
The the integer a process returns to its parent on termination, where 0 means success and non-zero signals a distinct failure is how a shell script or a CI job branches on your tool, so pick distinct values for distinct failures and document them. When a user interrupts a program with Ctrl-C, the shell reports status 130, the sum of 128 and the signal number for SIGINT, and a well-behaved tool lets that propagate instead of swallowing it.
The higher-level question is whether to hand your CLI to argparse, click, or typer. click wraps a function in decorators and generates the command, the help text, and the validation for you:
import click
@click.group()
def cli():
"""Flash, provision and test SensorNode boards."""
@cli.command()
@click.argument("image")
@click.option("--board", "-b", default="sn-01")
@click.option("--verify", is_flag=True)
def flash(image, board, verify):
"""Write a firmware image to a board."""
click.echo(f"flashing {image} to {board}")
if __name__ == "__main__":
cli()
typer goes one step further and derives the whole interface from a function's type hints, so the annotations you already write become the parser:
import typer
app = typer.Typer()
@app.command()
def flash(image: str, board: str = "sn-01", verify: bool = False) -> None:
"""Write a firmware image to a board."""
typer.echo(f"flashing {image} to {board}")
if __name__ == "__main__":
app()
This is where type hints and docstrings stop being decoration. typer reads the annotations to decide that image: str is a positional argument, board: str = "sn-01" is an option with a default, and verify: bool is a flag. Editors read the same hints for autocompletion, and a checker such as mypy uses them to catch a call with the wrong types. Write them for the machines, as well as for the next engineer.
The choice is a trade between a dependency and polish. argparse is in the standard library, so a single-file tool that must run on a minimal build host with nothing installed uses it and pays no dependency cost. click adds a dependency but gives richer help, better errors, and shell completion for free. typer adds the least boilerplate and suits a team that already annotates everything. For a tool you distribute to machines you do not control, argparse's zero dependencies win; for an internal team tool, typer or click win on the speed of writing.
A flashing tool that exits 0 when the write failed will corrupt an automated provisioning line, because the next step runs on a board that is not flashed. Return a non-zero code on every failure, keep the codes distinct, and print the reason to stderr. The CI and the factory script read the code, not the log, so the code is the contract.
Common mistakes and how to fix them
A subcommand that is missing produces AttributeError: 'Namespace' object has no attribute 'func'. Cause: add_subparsers without required=True, so no verb gives an empty namespace. Fix: pass required=True (Python 3.7 and later).
A boolean option always reads True. Cause: type=bool does not convert the way you hope, because the string "False" is truthy. Fix: use action="store_true" for a flag with no value.
An import pulls in the wrong copy of the package. Cause: running from a directory where the package name is shadowed, because the current directory is on sys.path. Fix: use the src layout and install the package, so there is one copy and the tests exercise it.
A relative import fails with attempted relative import with no known parent package. Cause: running the file directly instead of through the package. Fix: run it with python -m devkit.cli or give the project a console script.
A tool returns 0 even when it failed. Cause: the function returns the result but main is not wired to sys.exit. Fix: return an int from main and call sys.exit(main()) in the guard.
Try it
1 min readThe lab for this lesson has three parts. First, package a small tool such as a flash or log utility in src layout with a pyproject.toml and a [project.scripts] entry point, install it editable with pip install -e ., and run the installed command. Second, take a script that parses sys.argv by hand and rewrite it with argparse subcommands and meaningful exit codes, then try --help and a few bad inputs. Third, build a wheel with python -m build and inspect its contents with unzip -l to see exactly what ships. Before you start, re-read the entry-point internals and the lock-file section, and experiment with argparse's error messages in the REPL.
Key takeaways
- A module is one .py file and a package is a directory of modules; both are reached through the import system.
- import searches sys.path in order and caches results in sys.modules, and sys.path[0] depends on how you launched the program.
- The __main__ guard and python -m pkg.mod let one file be both a script and an importable module without side effects.
- pyproject.toml declares project metadata and the build backend, and [project.scripts] maps command names to module:function entry points.
- A wheel is a pre-built artifact and an sdist is the source tree; pip install -e . makes a project editable without copying it.
- Pins and lock files, not bare requirement names, make a build host reproducible; uv makes this fast.
- argparse gives you parsing, help text, types and exit code 2 on bad input; click and typer trade less boilerplate for an extra dependency.
- Type hints and docstrings are read by tools such as typer, editors and mypy, so write them for machines, not just humans.
Reflect
- Explain to a colleague, in two sentences: explain the roles of modules, packages and entry points, and state why a tool is split into them.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Official docsThe Python Tutorial: Modules
- Official docsThe import system
- Official docsargparse: parser for command-line options and sub-commands
- Official docssys: system-specific parameters and functions
- Official docsPackaging Python Projects
- Specificationpyproject.toml specification
- SpecificationPEP 621: Storing project metadata in pyproject.toml
- SpecificationPEP 517: A build-system independent format for source trees
- SpecificationPEP 518: Specifying minimum build system requirements
- Official docsuv documentation
Official documentation first. Links checked when the lesson was published.