Build Your First Python Package with pyproject.toml
Python packages are important for software development as they promote modularity, simplify dependency management, and ensure smooth distribution and installation.
Let’s create a basic package structure and add the necessary files.
my_package/
├── pyproject.toml
├── README.md
├── my_package/
│ ├── __init__.py
│ └── module.py
- Create a new directory for your package, for example,
my_package
. - Inside the
my_package
directory, create the following files:
__init__.py
: An empty file to mark the directory as a Python package.module.py
: A simple Python module with some code.
3. Now, create a pyproject.toml
file in the root of your package directory. This file is used to configure various aspects of your project, including dependencies and build tools.
[build-system]
requires = ["setuptools", "setuptools-scm"]
build-backend = "setuptools.build_meta"
[project]
name = "my_package"
authors = [
{name = "Example Author", email = "author@example.com"}
]
description = "package description"
version = "0.0.1"
readme = "README.md"
requires-python = ">=3.7"
dependencies = [
"requests > 2.26.0",
"pandas"
]
pyproject.toml documentation
https://setuptools.pypa.io/en/latest/userguide/pyproject_config.html
4. Now, let’s add some code to module.py
. For example
def add(a: int, b: int):
"add two numbers"
return a + b
5. Lastly, Now generate the distribution. To build the package, use PyPA build:
$ pip install -q build
$ python -m build
And now it’s done! The .whl
file and .tar.gz
can then be distributed and installed.
dist/
my_package-0.0.1-py3-none-any.whl
my_package-0.0.1.tar
$ pip install dist/my_package-0.0.1-py3-none-any.whl
Or
pip install dist/my_package-0.0.1.tar
Conclusion
In conclusion, creating a Python package involves structuring your code, defining metadata, and distributing it for others to use. By organizing your project with a specific directory structure, creating module files, and writing metadata in pyproject.toml.
you can make your code easily shareable and installable. Documenting your package in a README.md
file provides essential information for users.
The distribution process involves building a package and uploading it to the Python Package Index (PyPI) using tools like setuptools
and twine
. Once uploaded, users can install your package with pip
and leverage the functionality you've provided in their projects.
This process fosters collaboration and code reuse within the Python community, allowing developers to share and integrate each other’s work easily. Overall, creating a Python package is a fundamental step in contributing to the open-source ecosystem and facilitating the growth of Python-based projects.