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

  1. Create a pyproject.toml with build backend and project metadata.
  2. Structure your package with a src/ layout.
  3. Build with python -m build.
  4. 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.md and LICENSE files 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__.py files 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.in or tool configs to exclude them.