
Recall first from Modules and packages
- 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.
- __init__.py turns a directory into a regular package and, through re-exports and __all__, defines the public API; a namespace package has no __init__.py and can span several directories.
Scripts versus importable code: __main__ and python -m
2 min readNow that code lives in modules and packages, this lesson answers how to turn a script into a well-structured, installable project.
The 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.
Key takeaways
- 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.
- The src layout keeps the package out of sys.path so tests import the installed copy, catching packaging errors the flat layout hides.
Reflect
- Explain to a colleague, in two sentences: structure a project in src layout with a pyproject.toml, and install it editable so a console_scripts command runs.
- 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 docsPackaging Python Projects
- Specificationpyproject.toml specification
- SpecificationPEP 621: Storing project metadata in pyproject.toml
- SpecificationPEP 518: Specifying minimum build system requirements
Official documentation first. Links checked when the lesson was published.