Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 38 ยท Projects and Practice

Project: Publish a Command-Line Package

Put the whole course together. Create a command-line package, test it, build a wheel by hand to see what is inside, install it, and prepare the release workflow.

Time to combine everything into one small, complete project: a command-line tool called wordtally that prints the most common words in some text. The code is tiny on purpose. The point is the journey from an empty folder to a package that a stranger can install with one command.

You will lay out the project, write the configuration, test it, then do something unusual: build a wheel by hand with Python's zipfile, install it, and run its command, so you see exactly what a build tool produces and what an installer does. The publishing steps happen on your computer and on PyPI, so those are shown as read-only commands.

Step 1: the layout

TEXT
wordtally/
  pyproject.toml
  README.md
  LICENSE
  CHANGELOG.md
  src/
    wordtally/
      __init__.py
      cli.py
      py.typed
  tests/
    test_cli.py
  .github/
    workflows/
      ci.yml
      release.yml

The src layout forces tests to use the installed package (see testing with pytest). py.typed ships your type hints to users of the package (type checking).

Step 2: the code

src/wordtally/cli.py holds the tool. It exposes a main() function that takes an optional argument list, which makes it easy to test and to use as an entry point:

Python
import argparse
import sys
from collections import Counter
from collections.abc import Sequence


def count_words(text: str, limit: int = 3) -> list[tuple[str, int]]:
    words = [w.strip(".,!?;:\"'()").lower() for w in text.split()]
    return Counter(w for w in words if w).most_common(limit)


def main(argv: Sequence[str] | None = None) -> int:
    parser = argparse.ArgumentParser(prog="wordtally", description="Show the most common words.")
    parser.add_argument("text", nargs="*", help="text to analyze (reads stdin if omitted)")
    parser.add_argument("-n", "--top", type=int, default=3, help="how many words to show")
    args = parser.parse_args(argv)

    text = " ".join(args.text) if args.text else sys.stdin.read()
    for word, count in count_words(text, args.top):
        print(f"{count:>4}  {word}")
    return 0

Step 3: pyproject.toml

TOML
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[project]
name = "wordtally"
version = "0.1.0"
description = "Show the most common words in some text."
readme = "README.md"
requires-python = ">=3.9"
license = "MIT"
license-files = ["LICENSE"]
authors = [{ name = "Your Name", email = "[email protected]" }]
keywords = ["text", "words", "cli"]
classifiers = [
    "Programming Language :: Python :: 3",
    "Environment :: Console",
    "Topic :: Text Processing",
]
dependencies = []

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

[project.urls]
Homepage = "https://github.com/you/wordtally"
Changelog = "https://github.com/you/wordtally/blob/main/CHANGELOG.md"

[dependency-groups]
test = ["pytest>=8", "coverage>=7"]
lint = ["ruff", "mypy"]

[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-ra --strict-markers"

[tool.ruff.lint]
select = ["E", "F", "I", "B", "UP"]

[tool.mypy]
strict = true

The tool has no runtime dependencies, which keeps installs fast and conflicts impossible. Anything you add later would go in dependencies with a wide range.

Step 4: develop and test

Terminal
uv sync                       # create .venv, install the package and groups
uv run wordtally "to be or not to be"
uv run pytest
uv run ruff check . && uv run ruff format --check .
uv run mypy src

Add the pre-commit hooks and the CI workflow from earlier lessons so these checks run automatically.

Step 5: what is in a wheel?

uv build (or python -m build) creates two files in dist/: an sdist (wordtally-0.1.0.tar.gz, the source) and a wheel (wordtally-0.1.0-py3-none-any.whl, ready to install). A wheel is just a ZIP file with a strict layout:

  • the package files (wordtally/__init__.py, wordtally/cli.py);
  • a wordtally-0.1.0.dist-info/ folder with METADATA (name, version, requirements...), WHEEL (format and tags), entry_points.txt (the commands) and RECORD (a list of every file with a hash and size).

The filename encodes compatibility: py3 (Python 3), none (no specific ABI), any (any platform) means a pure-Python wheel that installs everywhere.

The next example plays the role of the build backend. It assembles those files, writes the RECORD, packs the ZIP, then plays the installer: it installs the wheel and runs the wordtally entry point.

Python Build a wheel by hand, install and run it

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The output shows the files, the parsed compatibility tags, and the tool counting to and be twice. In real life, the build backend (hatchling, setuptools, uv_build...) does the assembling, but the result has the same shape, and the installer does the same unpacking and script creation.

Step 6: check before you publish

Terminal
uv build
uvx twine check dist/*               # metadata and README render correctly?
python -m venv /tmp/t && /tmp/t/bin/pip install dist/*.whl
/tmp/t/bin/wordtally "does it work?" # test the wheel in a clean environment

Rehearse on TestPyPI the first time. Add a trusted publisher on PyPI, then push a tag so the release workflow builds and publishes:

Terminal
git tag v0.1.0
git push origin v0.1.0

Finally, install it as a user would, from a clean environment: pipx install wordtally or uvx wordtally "hello hello world".

Extensions to try

  1. Add a --json flag and a new minor version, 0.2.0, with a changelog entry.
  2. Add a dependency such as rich for colored tables and see the lock file change.
  3. Make the version dynamic from Git tags with hatch-vcs.
  4. Build a zipapp of the tool.
  5. Add a Docker image that runs the tool, using the multi-stage pattern.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is a wheel file?

    A wheel is a built distribution: installers just unpack it and generate scripts.
  2. 2. What does the tag py3-none-any in a wheel filename mean?

    py3 is the Python tag, none means no specific ABI, and any means any platform.
  3. 3. Which file inside .dist-info lists every installed file with hashes and sizes?

    RECORD is used to verify and later uninstall the files that belong to the package.
  4. 4. Why test the built wheel in a clean environment before publishing?

    A clean install proves the artifact users get really works, which is the point of packaging.

Summary

  • A packaging project is source (src layout), pyproject.toml, tests, CI and a release workflow.
  • [project.scripts] creates the command; no runtime dependencies keeps installs simple.
  • A wheel is a ZIP of package files plus .dist-info metadata (METADATA, WHEEL, entry_points.txt, RECORD).
  • Check with twine check, install into a clean environment, rehearse on TestPyPI, then publish from a tag with trusted publishing.

Next: Project: Build a Mini Dependency Resolver