Sometimes the need arises to share code across different python projects. This can be achieved by extracting that code into a separate project and making it into a python package. This can be uploaded to the PyPi python package repository, however for private code this can be hosted on a Github private repo.

1. Project Setup

Hatch can be used to help us setup the project:

mkdir REPONAME
uvx hatch new PROJECTNAME

This creates the following basic structure:

. REPONAME
├── pyproject.toml
├── src
│   └── PROJECTNAME
│       ├── __about__.py
│       └── __init__.py
└── tests
    └── __init__.py

For a minimum working project, there are three things to do:
A. Add src/myscript.py with your code
B. In __init__.py import your functions: from .myscript import *
C.Check pyproject.toml has the correct metadata (e.g. choose an organisation for the repo if that’s not a personal one, for example)

Additionally, it is useful to add a the python .gitignore and a readme file:

curl -L https://raw.githubusercontent.com/github/gitignore/main/Python.gitignore -o .gitignore 
touch README.md

2. Upload to Github

After creating REPONAME on Github:

git add .
git commit -m 'initial commit'
git remote add origin git@github.com:USERNAME/REPONAME.git
git push

3. Installation into another project’s environment

With pip:

pip install git+https://github.com/USERNAME/REPONAME.git@main#egg=REPONAME

–force-reinstall can be added as an option to ensure this is updated if its been installed previously

With uv:

uv --reinstall git+https://github.com/USERNAME/REPONAME.git@main#egg=REPONAME

4. Usage in another project

Once the package is installed, it can be used in the following way:

from myscript import function

Check out the online book Python Packages for more advanced details.