Python Type Hints and Code Quality · Lesson 137 of 149

Python Project Layout and Packaging

What you will learn

  • A standard project layout: src/, tests/, README, pyproject.toml
  • What goes in pyproject.toml: build system, metadata, dependencies, scripts, tool settings
  • Editable installs with pip install -e .
  • Console scripts (commands that run your code)
  • Building a distributable package with python -m build
  • Versions, and a note on publishing

1. From script to project

A single file is enough for a small tool. When a program grows (several modules, tests, dependencies, other people), it needs a project structure so that it can be installed, tested, shared and maintained. The pieces come from earlier lessons: modules and packages (lessons 16.2 and 16.3), virtual environments and pip (lessons 16.5 and 16.6), tests (chapter 18) and style checks (lesson 19.3). This lesson puts them together.

2. A standard layout

Here is the layout of a small project called wordkit (a library of text helpers that also provides a command):

wordkit/                  ← the project folder (a git repository)
├── pyproject.toml        ← metadata, dependencies, tool settings
├── README.md
├── .gitignore
├── src/
│   └── wordkit/          ← the importable package
│       ├── __init__.py
│       ├── core.py
│       └── cli.py
└── tests/
    └── test_core.py
Item Purpose
pyproject.toml the one configuration file for the project (section 3)
README.md what the project is and how to use it (lesson 19.4)
.gitignore files git must not track: .venv/, __pycache__/, dist/, build/, *.egg-info/, tool caches
src/wordkit/ the package. Putting it under src/ means tests import the installed package rather than whatever sits in the current folder, which catches packaging mistakes
tests/ the test files, kept out of the package (lesson 18.3)

The "flat" alternative puts wordkit/ next to pyproject.toml without src/. It also works; the src layout is simply safer. For an application rather than a library (a web site, like the Django project behind this one), the layout follows its framework's conventions, but the same ideas about tests, requirements and documentation apply.

The package files:

src/wordkit/__init__.py:

"""wordkit: small helpers for counting and shortening text."""

from wordkit.core import count_words, shorten

__all__ = ["count_words", "shorten"]
__version__ = "0.1.0"

src/wordkit/core.py:

"""Core functions."""

from collections import Counter


def count_words(text: str) -> dict[str, int]:
    """Count how often each word appears (case-insensitive)."""
    return dict(Counter(text.lower().split()))


def shorten(text: str, width: int, placeholder: str = "...") -> str:
    """Cut ``text`` to at most ``width`` characters."""
    if width < len(placeholder):
        raise ValueError(f"width must be at least {len(placeholder)}")
    if len(text) <= width:
        return text
    return text[: width - len(placeholder)] + placeholder

src/wordkit/cli.py (the command-line entry point, lesson 17.8):

"""Command-line entry point."""

import argparse
import sys

from wordkit.core import count_words, shorten


def main(argv=None):
    parser = argparse.ArgumentParser(prog="wordkit", description="Text helpers.")
    sub = parser.add_subparsers(dest="command", required=True)
    count = sub.add_parser("count", help="count words in the text")
    count.add_argument("text")
    cut = sub.add_parser("shorten", help="shorten the text")
    cut.add_argument("text")
    cut.add_argument("--width", type=int, default=10)
    args = parser.parse_args(argv)

    if args.command == "count":
        for word, number in count_words(args.text).items():
            print(f"{word}: {number}")
    else:
        print(shorten(args.text, args.width))
    return 0


if __name__ == "__main__":
    sys.exit(main())
Quick check: why keep `tests/` outside the package folder?

The tests are not part of what users install, and tests that import the installed package check what users will actually get.

3. pyproject.toml

pyproject.toml is written in TOML, a simple settings format ([sections] and key = value). It has three kinds of content.

[build-system]
requires = ["setuptools>=77"]
build-backend = "setuptools.build_meta"

[project]
name = "wordkit"
version = "0.1.0"
description = "Small helpers for counting and shortening text."
readme = "README.md"
requires-python = ">=3.10"
license = "MIT"
authors = [{ name = "Example Author" }]
dependencies = []

[project.optional-dependencies]
dev = ["pytest", "ruff", "mypy"]

[project.scripts]
wordkit = "wordkit.cli:main"

[tool.setuptools.packages.find]
where = ["src"]

[tool.pytest.ini_options]
testpaths = ["tests"]

[tool.ruff]
line-length = 88
  1. [build-system]: which tool builds the package (here setuptools; others are hatchling, flit, poetry-core). Tools like pip read this to build your project.
  2. [project]: the metadata.
Key Meaning
name, version the package name on PyPI and its version (section 6)
description, readme short summary and long description
requires-python the Python versions supported
license an SPDX licence name such as MIT (an old table form { text = "MIT" } is deprecated and gave a build warning)
dependencies packages needed to use it, with version ranges (lesson 16.6)
optional-dependencies extras, such as dev tools: pip install ".[dev]"
scripts console scripts: commands created at install time
  1. [tool.*]: settings for other tools (pytest, ruff, black, mypy), as in lesson 19.3.

The scripts entry wordkit = "wordkit.cli:main" says: create a command named wordkit that calls the function main in module wordkit.cli.

4. Installing for development: pip install -e

Inside a virtual environment (lesson 16.5), from the project folder:

python -m pip install -e ".[dev]"
  • . means "the project in this folder".
  • -e means editable: pip links to your source files instead of copying them, so changes take effect immediately with no reinstall.
  • [dev] also installs the optional development dependencies.

After that, the package is importable from anywhere in that environment, and the tests, checks and command all work:

$ python -m pytest -q
...                                                                      [100%]
3 passed in 0.03s

$ wordkit count "the cat and the hat"
the: 2
cat: 1
and: 1
hat: 1

$ wordkit shorten "Hello, world" --width 8
Hello...

$ python -m mypy src
Success: no issues found in 3 source files

$ python -m ruff check .
All checks passed!

(All of these were run for this lesson in a fresh environment; the wordkit command was started from the environment's Scripts folder, which is where pip puts console scripts on Windows, and bin on macOS and Linux.) The test file used the installed package:

import pytest

from wordkit import count_words, shorten


def test_count_words():
    assert count_words("Go go stop") == {"go": 2, "stop": 1}


def test_shorten_long_text():
    assert shorten("Hello, world", 8) == "Hello..."


def test_shorten_rejects_tiny_width():
    with pytest.raises(ValueError):
        shorten("Hello", 2)

With the package installed, import wordkit finds it at .../wordkit/src/wordkit/__init__.py: the editable install points to your source folder.

5. Building a distribution

To give the project to someone else, build distribution files:

python -m pip install build
python -m build

This creates a dist/ folder with two files:

wordkit-0.1.0.tar.gz               (the "sdist": source distribution)
wordkit-0.1.0-py3-none-any.whl     (the "wheel": a ready-to-install archive)

A wheel is a zip file; this one contained exactly:

wordkit/__init__.py
wordkit/cli.py
wordkit/core.py
wordkit-0.1.0.dist-info/METADATA
wordkit-0.1.0.dist-info/WHEEL
wordkit-0.1.0.dist-info/entry_points.txt
wordkit-0.1.0.dist-info/top_level.txt
wordkit-0.1.0.dist-info/RECORD

The three source files are there, and the tests are not. The *.dist-info files carry the metadata, and entry_points.txt records the wordkit command. Anyone can now run python -m pip install dist/wordkit-0.1.0-py3-none-any.whl into their own environment. The names py3-none-any mean it works on any Python 3 and any system, because it contains only Python code (packages with compiled parts get platform-specific wheels).

dist/ and build/ can be rebuilt at any time, so they belong in .gitignore.

6. Versions and publishing

Versioning. The common scheme is semantic versioning: MAJOR.MINOR.PATCH.

Change Raise
bug fix, nothing else changes PATCH: 0.1.0 → 0.1.1
new feature, still compatible MINOR: 0.1.1 → 0.2.0
change that can break users' code MAJOR: 0.2.0 → 1.0.0

Keep a CHANGELOG.md (lesson 19.4) and tag releases in git (git tag v0.1.0). Keep the version in one place (here pyproject.toml; __version__ in __init__.py must be kept in step, or read from the installed metadata).

Publishing a package means uploading dist/* to PyPI, the index that pip install uses (lesson 16.6), using a tool called twine and an account with an API token. Before publishing, check the name is free and suitable, that there are no secrets in the files, that the licence is right, and that the README makes sense. Test on TestPyPI (a practice index) first. Uploads to PyPI cannot be undone: a published version number can never be reused. This lesson did not upload anything; wordkit is only a teaching example.

Many projects are never published: they are installed from the repository (pip install git+https://...) or deployed as an application. The same layout works for all of these.

7. A checklist for a new project

  1. Create a folder and git init (with a .gitignore).
  2. Create a virtual environment .venv (lesson 16.5) and do not commit it.
  3. Add pyproject.toml, README.md, src/<package>/, tests/.
  4. python -m pip install -e ".[dev]".
  5. Write tests (chapter 18), type hints (lesson 19.1), docstrings (lesson 19.4).
  6. Run ruff format, ruff check, mypy, pytest (lesson 19.3) before every commit; automate them with a pre-commit hook or continuous integration.
  7. Tag versions; keep a changelog.

Worked example: wordkit, from layout to wheel

The whole workflow of this lesson, as it was run in a fresh virtual environment:

Step Command Result
1. create files the layout and files in section 2 and the pyproject.toml in section 3 a 3-module package, tests, README
2. install for development python -m pip install -e ".[dev]" wordkit 0.1.0 installed along with pytest, ruff, mypy
3. run the tests python -m pytest -q 3 passed
4. try the command wordkit count "the cat and the hat" the: 2, cat: 1, and: 1, hat: 1
5. static checks python -m mypy src, python -m ruff check . Success: no issues found in 3 source files, All checks passed!
6. build python -m build wordkit-0.1.0.tar.gz and wordkit-0.1.0-py3-none-any.whl
7. inspect the wheel list its contents the package files and the metadata; no tests

Two details worth remembering from the run:

  • The first build used the older form license = { text = "MIT" } and printed a deprecation warning. Changing it to license = "MIT" (with setuptools>=77 in requires) removed the warning: tools change, so read build warnings.
  • import wordkit located the code under src/wordkit/, proving the editable install pointed at the source folder, so every edit was visible at once.

Nothing was uploaded anywhere. The package, its author name and its text are made up for the lesson.

Common mistakes

  • Committing .venv, dist/, build/ or *.egg-info.
  • Running code from the wrong folder so that imports work by accident, but not after installing (the reason for the src layout).
  • Forgetting __init__.py or where = ["src"], so the package is missing from the wheel.
  • Putting tests inside the installed package by accident.
  • Inconsistent versions in two files.
  • Unpinned or missing dependencies in pyproject.toml.
  • Publishing a package with secrets, or an unsuitable name.
  • Ignoring deprecation warnings from the build tools.

Key takeaways

  • A tidy project has pyproject.toml, README.md, .gitignore, a src/<package>/ folder and a tests/ folder.
  • pyproject.toml holds the build system, project metadata (name, version, dependencies, Python version, licence), console scripts, and tool settings.
  • python -m pip install -e ".[dev]" installs the project for development inside a virtual environment, so imports, tests and the command work.
  • python -m build creates a source archive and a wheel in dist/; those are rebuilt, not committed.
  • Use semantic versions; publishing to PyPI is permanent, so check carefully and try TestPyPI first.

Practice

1. What does the -e in pip install -e . mean?

Show answer

Editable: pip links to your source folder, so changes take effect without reinstalling.

2. In pyproject.toml, what does wordkit = "wordkit.cli:main" under [project.scripts] create?

Show answer

A command named wordkit that runs the function main in the module wordkit.cli.

3. Why put the package under src/?

Show answer

Tests and scripts then import the installed package instead of whatever is in the current folder, which reveals packaging mistakes early.

4. Which command builds a wheel?

Show answer

python -m build (after python -m pip install build); the wheel appears in dist/.

5. Which version number comes after 1.4.2 when you fix a bug? When you add a compatible feature? When you break compatibility?

Show answer

1.4.3; 1.5.0; 2.0.0.

6. Why should you not commit the dist/ folder?

Show answer

It contains generated files that can be rebuilt from the source at any time, and committing them clutters the repository and gets out of date.