Module 22 · Lesson 6 of 64

From script to a proper project

Turn a script into a well-structured, installable project using the __main__ guard, the src layout, and a pyproject.toml with entry points.

  • Beginner to advanced
  • 7 min read
  • 10 min lab
What you will need

Ubuntu 24.04 (WSL2, a VM, or a container) with Python 3.11 or newer (Ubuntu 24.04 ships 3.12); a terminal; no board needed for this lesson

Your place in the module
By the end you can 2 objectives
  • Structure a project in src layout with a pyproject.toml, and install it editable so a console_scripts command runs.
  • Separate a script's importable code from its side effects with the __main__ guard, and run a package module with python -m.
Video coming soonFrom script to a proper project
The video for this lesson is being recorded. Read the lesson below in the meantime.
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.
01

Scripts versus importable code: __main__ and python -m

2 min read

Now 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:

python
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:

bash
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.

One file, three livesRun as scriptImport asmodulepython -m pkg__name____main__devkit__main____package__emptydevkitdevkitRelative importsfailworkworkTop-level sideeffectsrunrun on importrun
One file run as a script, imported as a module, and run with python -m: the three values of __name__ and __package__.
02

Project layout: src layout versus flat layout

2 min read

A 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:

text
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:

text
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.

In the src layout the package is not reachable from the project root: devkit/__init__.py does not resolve, only src/devkit/__init__.py does. That gap is what forces an install before import devkit works.

  • cwd: /home/learner/devkit-project
  • value: devkit/__init__.py

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.

Flat layout versus src layoutFlat layoutsrc layoutPackage livesdevkit/ atthe rootsrc/devkit/Tests importthe sourcetreethe installedcopyBroken packagingmasked, testspasscaught,import failsBest forapps neverimporteddistributedpackages
Flat layout keeps the package at the root; src layout moves it under src/ so tests import the installed copy.
03

pyproject.toml: metadata, build backends, and entry points

4 min read

The 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:

toml
[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 modern pyproject.toml arrived in steps: PEP 518 (2016) declared build requirements, PEP 517 (2017) decoupled the backend from the frontend, and PEP 621 (2020) standardised project metadata.

  • events: [{"date": "2016", "label": "PEP 518 accepted", "detail": "pyproject.toml becomes the place to declare build-system requirements such as requires and build-backend."}, {"date": "2017", "label": "PEP 517 accepted", "detail": "A build-system independent format: a small interface between a build frontend and a build backend."}, {"date": "2020", "label": "PEP 621 accepted", "detail": "Project metadata such as name, version and dependencies is standardised in pyproject.toml, replacing setup.py."}]

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 . When the package is installed, pip generates a 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.

Step by stepWhat happens when you run the devkit command
  1. The shell finds the wrapper: devkit is an executable in the environment's bin directory, on PATH.

  2. The wrapper imports the module: it imports devkit.cli, executing its top-level code once.

  3. The wrapper calls main: it calls the function named by the entry point, with no arguments.

  4. main parses the arguments: argparse reads sys.argv and produces a namespace.

  5. 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:

text
[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.

The tables of pyproject.tomlpyproject.toml[build-system]how to buildrequiresbuild-backend[project]metadata, PEP 621name, versionrequires-pythondependencies[project.scripts]commandsdevkit = devkit.cli:mainpyproject.toml[build-system]how to buildrequiresbuild-backend[project]metadata, PEP 621name, versionrequires-pythondependencies[project.scripts]commandsdevkit = devkit.cli:main
The three tables of a pyproject.toml: the build system, the project metadata, and the command entry points.

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
  1. 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.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. 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

Find your next step

↑ ↓ to move · Enter to open · Esc to close