🎓 A1Learner
🔍

Python Packaging a Project

Packaging is preparing code so other people can install it on their own computers. A package is a folder of modules with an __init__.py file.

One file, one job

This small package is named greetkit. Its messages.py file holds one small function.

# greetkit/messages.py
def hello(name):
    return f"Hello, {name}!"

The init file builds the API

__init__.py imports hello from messages. Users then reach hello through the package name.

# greetkit/__init__.py
from .messages import hello

__version__ = "1.0"

Use the package from outside

This program sits next to the greetkit folder. It uses the package without touching the files inside.

import greetkit

print(greetkit.hello("Ada"))
print(greetkit.__version__)

The build step, in words

Run in the project folder, this command makes an sdist and a wheel. The build tool is external, so this lesson names the step but does not run it.

python3 -m build

Example

# File: original/greetkit/messages.py
def hello(name):
    return f"Hello, {name}!"

# File: original/greetkit/__init__.py
from .messages import hello

__version__ = "1.0"

# File: fresh/use_greetkit.py
import greetkit

print(greetkit.hello("Ada"))
print("Version:", greetkit.__version__)

Key points

  • Package: a folder of modules with an __init__.py file
  • API: the names a package offers for other programs to use
  • Use __init__.py to build the tidy public API of the package
  • Version: keep the version text in one place, such as __version__ in __init__.py
  • Source distribution, short name sdist: a file that packs your source code for sharing
  • Wheel: a ready-to-install package file.
  • Python installs it without building anything first
  • Use python3 -m build to make an sdist and a wheel.
  • The build tool is not part of the standard library
  • Entry point: a command name a package can install.
  • It lets users run your tool by name
  • PYTHONPATH: an environment setting that adds folders to the import search list
  • Packaging prepares code so other people can install it on their own computers.

In this example, the whole tree lives in one scratch folder. The greetkit package starts in a folder named original. Then the greetkit folder is copied into a second folder named fresh. The fresh folder also holds use_greetkit.py. The run happens inside the fresh folder, with this command: PYTHONPATH=. python3 use_greetkit.py. PYTHONPATH adds the fresh folder to the places Python searches. The import finds the copied package, not the original. No install step was needed. That is why this trick is called a poor man's install.

Note

Copying a folder works only while that folder stays on the search list.

A real install puts the package where every program can find it.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

Where should a package keep its version text?