Part 4: Python Packaging

Turning a script into something you can actually hand to someone.

Where we are

_images/p4-recap.svg

What packaging buys you

  • installable with pip install, from anywhere

  • importable by other projects, with no PYTHONPATH fiddling

  • runnable as a real command, not python /some/long/path/script.py

  • uninstallable cleanly, versioned, and depended-upon

The problem, concretely

_images/p4-import-anywhere.svg

Where we start

number_magic.py
def addition(arg1, arg2):
    """
    This function adds the first and the second argument.

    :param arg1: the first summand
    :return:     the sum of both summands
    """
    return arg1 + arg2

Five steps

_images/p4-five-steps.svg

1. A folder makes it a package

some_directory/
   plain_magic/
      __init__.py
      number_magic.py

2. pyproject.toml makes it installable

[project]
name = "plain_magic"
version = "0.0.1"
requires-python = ">=3.10"
dependencies = ["click"]

3. An entry point makes it a command

_images/p4-entry-point.svg

4. tox and CI run the tests for you

[tox]
envlist = py310
isolated_build = True

[testenv]
deps = pytest
commands = pytest

5. A linter keeps it tidy

ruff check .
ruff check --fix .

…and .gitignore keeps it clean

Virtual environments, caches and build artifacts do not belong in git.

The whole journey

_images/p4-script-to-package.svg

Over to you

Build the package, add a command, wire up CI, and lint it.

Part 4 tasks →