Part 4: Python Packaging¶
Note
Part 4 of 4, the final part of the curriculum. Unlike Parts 1–3, this part doesn’t use a cookiecutter template to generate a starter project for you — you build the package yourself, from a single plain Python file, using the tasks below.
See also
A condensed slide deck of this part is available for presenting: Part 4 slides (see Presentation Slides).
Why packaging?¶
By now (Parts 1–3) you’ve written code, tested it, and documented it. But
so far, “using” that code has meant running a script directly out of a
folder you happen to be sitting in. Packaging is what turns a folder of
.py files into something that can be:
installed with
pip installfrom anywhere on your system, not just when your terminal happens to be in the right directory (see Prerequisites if “your terminal being in the right directory” doesn’t mean much to you yet)imported by other projects (
import my_package) without manually fiddling withPYTHONPATHrun as a proper command (
my-command --some-option) instead ofpython /some/long/path/script.pyuninstalled cleanly, versioned, and depended-upon by other packages
None of this is strictly required to write working code — but it’s the difference between a script that works on your machine, today, and software that’s usable, shareable, and maintainable by anyone (including future you).
This part’s tasks are built around the Kiwi Python Package Template, a cookiecutter template that bundles exactly the packaging features explained below. For the full, detailed reference on each feature, see the template’s own documentation — the tasks below link out to the specific relevant sections as you need them.
The starting point¶
The tasks below have you build a package around this single function, which starts out as a plain, standalone Python file with no package structure around it at all:
def addition(arg1, arg2):
"""
This functions adds the first and the second argument.
:param arg1: the first summand
:type arg1: float
:param arg2: the second and last summand
:type arg2: float
:return: the sum of both summands
:rtype: float
"""
return arg1 + arg2
Over the three tasks that follow (Basic Packaging,
Configure Continuous Integration, Conventions), you’ll turn this into:
a proper Python package (a folder importable by name), an installable
package (via pyproject.toml), a package with a command line interface
(via click), a package with automated tests and CI, and finally a
package that enforces its own coding conventions via a linter. Each of
these is a small, real step — by the end you’ll have rebuilt, piece by
piece, every mechanism the packages you generated in Parts 1–3 already came
with for free.