How do I package and distribute a Python project?
· Category: Python Programming
Short answer
Modern Python packaging uses pyproject.toml to define build system requirements, metadata, and dependencies. You can build a wheel with python -m build and publish it to PyPI using twine.
Steps
- Create a
pyproject.tomlwith build backend and project metadata. - Structure your package with a
src/layout. - Build with
python -m build. - Upload with
twine upload dist/*.
[build-system]
requires = ["setuptools>=61.0", "wheel"]
build-backend = "setuptools.build_meta"
[project]
name = "mypackage"
version = "0.1.0"
description = "A sample package"
readme = "README.md"
requires-python = ">=3.9"
dependencies = ["requests>=2.31"]
Tips
- Use
src/layout to prevent accidental imports from the repository root. README.mdandLICENSEfiles improve package discoverability and compliance.- Test your package installation in a fresh virtual environment before publishing.
- Use
twine check dist/*to validate metadata before uploading.
Common issues
- Missing
__init__.pyfiles in subpackages cause import errors in older tools. - Version conflicts between build-time and runtime dependencies create hard-to-debug failures.
- Accidentally publishing secrets or large test files to PyPI is a security risk; use
MANIFEST.inor tool configs to exclude them.