35.Packaging – pyproject, build, publish
Packaging is a crucial aspect of Python development, enabling developers to distribute reusable code. Modern Python packaging has evolved to embrace standardized configuration files and streamlined build tools. This lesson explores the role of pyproject.toml, tools like setuptools and poetry, and the process of publishing packages to PyPI.
pyproject.toml
The pyproject.toml file is a standardized configuration file introduced by PEP 518. It defines build system requirements and project metadata. It replaces setup.py and setup.cfg in many modern workflows and is supported by tools like setuptools, poetry, and flit.
Example:
[project]
name = “example_package”
version = “0.1.0”
description = “An example Python package”
authors = [{name = “Jane Doe”, email = “jane@example.com”}]
dependencies = [“requests”]
[build-system]
requires = [“setuptools”, “wheel”]
build-backend = “setuptools.build_meta”
Build Tools
Python offers several tools for building packages. The most common are setuptools and poetry.
Using setuptools:
Setuptools is a legacy tool still widely used. With pyproject.toml, you can build your package using:
python -m build
Using poetry:
Poetry simplifies dependency management and packaging. It uses pyproject.toml exclusively.
To build a package:
poetry build
Publishing to PyPI
Once a package is built, it can be published to PyPI using twine. Twine securely uploads distributions to PyPI.
Steps:
Build the package:
python -m build
2. Upload using twine:
twine upload dist/*
Best Practices
– Use pyproject.toml for configuration
– Include a README, LICENSE, and tests
– Use semantic versioning
– Test your package locally before publishing
– Automate builds and uploads with CI/CD
Common Pitfalls
– Missing metadata in pyproject.toml
– Incorrect build-backend configuration
– Forgetting to include required files in MANIFEST.in
– Uploading broken distributions
– Not testing across Python versions