So you have created your Python library and you would like to use it in your projects. You found out that packaging your library and installing with pip is the right way, but how exactly can you achieve this. Let’s find out!!
The Structure
The directory structure of your package should be like the one below:
example-package/
- src/
- package/
- package files ...
- LICENSE
- README.md
- pyproject.toml
The most important file from above is the pyproject.toml. This is the new standard way for Python packaging (as of PEP 621)
Pyproject.toml
The minimal information that you can put on your pyproject.toml is the below:
[project]
name = "example-package"
version = "1.0.0"
Out of the box (in other words by default) pyproject.toml
defaults to using the setuptools
as a build system for our package. However if you would like to explicitly define the build system for better readability in the future or use an alternative you can include it in your pyproject.toml
file. Thus we can add the below in our file:
[build-system]
requires = ["setuptools>=70.0"]
build-backend = "setuptools.build_meta"
Building the package
Before continuing to build our package we need to have installed in our system the build
package (https://github.com/pypa/build).
Firstly we create a python virtual environment and then we can install it by running:
python3 -m venv venv
pip install build
Then we can navigate in our project directory “example-package” and run:
python3 -m build
This will create a new directory “dist” inside our main project directory with two files, the output of the command line should look like this:
Successfully built example_package-1.0.0.tar.gz and example_package-1.0.0-py3-none-any.whl
That's it 🎉 !! Our package ready! In a next post we will find out how to distribute your package privately or publicly (depending on your use case).