For years I maintained Python projects with a familiar ritual: a setup.py that grew barnacles, a requirements.txt that conflicted with setup.cfg, and a README that explained which pip flags to use in which order. It worked until it didn't — usually when a new teammate tried to set up the project, or when CI built a slightly different environment than my laptop. The shift to pyproject.toml as the single source of truth, combined with uv as a fast, unified toolchain, has finally made Python packaging predictable. In my experience, once you understand what belongs where in pyproject.toml and how uv handles resolution and environments, you stop fighting packaging and get back to shipping code.
Why setup.py and requirements.txt Ran Out of Road
Before PEP 517 and PEP 621, packaging was split across multiple files with overlapping responsibilities. setup.py was executable code, which meant installing a package could execute arbitrary Python. setup.cfg tried to make it declarative, but adoption was uneven. requirements.txt pinned versions for deployment, while setup.py declared abstract dependencies, and there was no standard way to keep them consistent.
I’ve found that this split created three recurring problems. First, reproducibility suffered because pip install -r requirements.txt without a lock file meant two installs a week apart could resolve different transitive dependencies. Second, tool configuration was scattered — flake8 in .flake8, mypy in mypy.ini, pytest in pytest.ini — making it hard to know what applied. Third, bootstrapping was slow and fragile, especially on CI where you had to create a virtual environment, upgrade pip, install build dependencies, then install the project.
The imperative versus declarative shift
The core change in pyproject.toml is that metadata is declarative and static. Build tools can read it without executing code, linters and type checkers can find their config in one place, and installers can reason about dependencies before downloading anything. The Python Documentation on packaging now treats pyproject.toml as the canonical location for project metadata, with setup.py retained only for backward compatibility or complex dynamic builds.
If you still have a setup.py in a new project, you’re opting into legacy complexity. I migrated a mid-sized service last year from setup.py + requirements*.txt to a single pyproject.toml and removed over 120 lines of imperative logic that existed only to read the README or infer the version from git tags.
Dissecting a Production-Grade pyproject.toml File
A well-structured pyproject.toml does three jobs: it tells build backends how to build a wheel, it tells installers what your project is and what it needs, and it configures the tools you run daily. Keeping those concerns separate but co-located is what makes the file powerful.
Project metadata under [project]
The [project] table is defined by PEP 621 and is understood by all modern tools — pip, uv, Hatch, PDM, and Poetry (with compatibility shims). This is where you declare name, version, Python requirement, dependencies, and optional groups. In my experience, the most common mistake is pinning too tightly in dependencies. Abstract dependencies should allow ranges; pins belong in the lock file.
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
name = "acme-ingest"
version = "0.4.2"
description = "Pipeline for ingesting vendor feeds into S3 and Postgres"
readme = "README.md"
requires-python = ">=3.11"
license = { text = "MIT" }
authors = [{ name = "Platform Team", email = "platform@acme.example" }]
keywords = ["etl", "ingest", "pipeline"]
classifiers = [
"Programming Language :: Python :: 3",
"Framework :: Pydantic",
]
dependencies = [
"httpx>=0.27,<1",
"pydantic>=2.6",
"sqlalchemy>=2.0",
"tenacity>=8.2",
]
[project.optional-dependencies]
dev = ["pytest>=8.1", "pytest-asyncio>=0.23", "ruff>=0.5.0", "mypy>=1.10"]
docs = ["mkdocs>=1.5", "mkdocs-material>=9.5"]
[project.urls]
Homepage = "https://github.com/acme/acme-ingest"
Changelog = "https://github.com/acme/acme-ingest/blob/main/CHANGELOG.md"
[project.scripts]
acme-ingest = "acme_ingest.cli:main"
Co-locating tool configuration
One of the biggest quality-of-life wins is [tool.*]. Instead of five dotfiles, you configure Ruff, Mypy, Pytest, and Coverage in one place, versioned alongside the code. This also guarantees that contributors and CI use identical settings.
[tool.ruff]
line-length = 100
target-version = "py311"
[tool.ruff.lint]
select = ["E", "F", "I", "B", "UP", "SIM"]
ignore = ["SIM108"]
[tool.mypy]
python_version = "3.11"
strict = true
warn_return_any = true
exclude = ["tests/fixtures"]
[tool.pytest.ini_options]
testpaths = ["tests"]
asyncio_mode = "auto"
addopts = "-q --strict-markers"
[tool.coverage.run]
source = ["acme_ingest"]
branch = true
I've moved almost all projects to this layout. When type checking matters for production code, having [tool.mypy] and [tool.ruff] next to dependency declarations removes the "works on my machine" drift that used to come from global tool configs. If you are standardizing types across a codebase, the patterns in Python Type Hints: A Practical Guide for Production Code fit naturally into this same file.
Choosing Your Build Backend: Hatchling, Setuptools, and Flit Compared
The [build-system] table does not specify how your package behaves at runtime — it specifies which backend builds the sdist and wheel. Your choice affects build speed, defaults, and how you manage package discovery and versioning.
In practice, most intermediate Python projects are well served by Hatchling. It is fast, has no legacy baggage, follows standards closely, and handles package discovery without needing a MANIFEST.in. Setuptools is the most flexible for complex extensions or custom build steps, but that flexibility often means more configuration. Flit is excellent for pure-Python packages with simple layouts but can feel limiting if you need editable installs with src layouts or binary extensions.
Here is how I evaluate them when starting a new service or library:
| Capability | Hatchling | Setuptools | Flit / Flit Core |
|---|---|---|---|
| Build speed and isolation | Very fast, no setup.py emulation | Slower, compatibility layers for legacy projects | Fast for pure-Python, minimal overhead |
| Src layout and package discovery | Automatic with sensible defaults, explicit [tool.hatch.build] |
Requires [tool.setuptools.packages.find] or setup.py shim |
Assumes flat or src layout, less configurable |
| Versioning from VCS | Plugin via hatch-vcs | Via setuptools-scm | Via flit-vcs (external) |
| Best fit | New applications and libraries, my default | Projects with C extensions or complex builds | Small pure-Python libraries |
Unless you need to compile extensions or run custom commands during build, start with Hatchling. You can always switch backends later — because metadata lives in [project], the backend is an implementation detail. I've switched a library from Setuptools to Hatchling in under an hour with no changes for consumers.
Replacing pip, venv, and pip-tools with a Single uv Workflow
uv is a single Rust binary from Astral that replaces pip, pip-tools, venv/virtualenv, and parts of pyenv. What matters is not just that it is 10-100x faster at resolving and installing — though it is — but that it unifies three workflows that used to require different tools.
For context on why isolation matters and how virtual environments work under the hood, I still point new developers to Python Virtual Environments: Why They Matter and How to Use Them. uv automates that isolation instead of asking you to manage it manually.
Day-to-day commands that replace the old stack
Where I used to run python -m venv .venv && source .venv/bin/activate && pip install -r requirements-dev.txt, I now run:
# Create a virtual environment with a specific Python if needed
uv venv --python 3.11 --seed
# Install the project and all dependency groups from pyproject.toml
uv sync --all-groups
# Add a new runtime dependency (updates pyproject.toml and uv.lock)
uv add "httpx>=0.27,<1"
# Add a dev-only group without touching runtime deps
uv add --group dev "pytest-asyncio>=0.23"
# Upgrade a single package while respecting version bounds
uv lock --upgrade-package pydantic
# Run a tool without polluting the environment
uv run ruff check .
uv run pytest -q
Two details here save real time. First, uv sync is deterministic against uv.lock and will create the environment if it does not exist, so CI and local setups run the same command. Second, uv run automatically syncs the environment before execution, which eliminates the classic error where you run tests against an outdated environment.
How resolution differs from pip
pip resolves independently on each install, while uv uses a universal resolver that can solve for all Python versions and dependency groups at once. In my experience, this catches conflicts earlier — for example, when a dev dependency constrains a library that your runtime needs at a different major version, uv lock fails fast with a clear error instead of letting you discover it only on CI.
The speed change is also practical, not just cosmetic. Cold installs of a 150-dependency data pipeline that took ~90 seconds with pip now take ~8 seconds with uv on the same runner. That changes behavior: developers actually recreate environments from scratch instead of trying to incrementally patch them.
Locking and Syncing for Reproducible Environments with uv.lock
Reproducibility comes from separating abstract dependencies (what you accept) from locked dependencies (what you tested). pyproject.toml declares the former; uv.lock records the latter.
After any change to [project] or dependency groups, uv lock recomputes the full dependency graph and writes uv.lock with exact versions, hashes, and markers. You commit uv.lock for applications and services. For libraries, you may commit it for CI reproducibility but you publish only the range constraints — consumers resolve their own graph.
# Inspect what would change before committing
uv lock --dry-run
# Sync environment exactly to the lock file (removes extraneous packages)
uv sync --frozen
# For Docker/CI: install without dev groups, reproducible and fast
uv sync --frozen --no-dev --no-editable
# Export a requirements.txt for tools that need it
uv export --format requirements-txt --no-hashes -o requirements.txt
uv export --format requirements-txt --group dev -o requirements-dev.txt
Structuring dependency groups sanely
PEP 735 introduces [dependency-groups] as the standard replacement for ad-hoc [tool.poetry.group] or [project.optional-dependencies] used for development. I’ve found the cleanest split is:
dependencies for runtime, [dependency-groups] for local development and CI, and [project.optional-dependencies] only for extras that consumers might install (like pip install acme-ingest[docs]). This keeps publishing minimal while giving contributors a full environment with uv sync --all-groups.
One operational tip: set UV_FROZEN=true in CI if you want to guarantee that CI never updates the lock file implicitly. If the lock is stale, the job fails instead of silently building with different versions — which is exactly what you want for a reproducible pipeline. For teams scaling test suites, pairing a locked environment with patterns from Pytest Patterns That Scale: Fixtures, Mocks and Parametrize eliminates a whole class of flaky failures caused by transitive upgrades.
Publishing to PyPI with Trusted Publishing and Build Isolation
Building and publishing is where many teams introduce supply-chain risk without realizing it. The modern workflow uses isolated builds and OIDC-based Trusted Publishing so you don’t need to store a PyPI token at all.
A clean build does three things: it verifies that your sdist contains the right files, it produces a wheel with correct metadata, and it checks that the project installs from scratch. With uv, that is:
# Build sdist and wheel in an isolated environment
uv build
# Verify metadata and that long_description renders
uv run twine check dist/*
# Inspect wheel contents (should not include tests or .env files)
uv run bash -c "unzip -l dist/*.whl | head -n 50"
# Publish via OIDC if configured, no token needed on GitHub Actions
uv publish --trusted-publishing always
To enable Trusted Publishing, you register your GitHub repository as a trusted publisher on PyPI, then call uv publish from an Action that has id-token: write permission. I migrated two internal libraries to this and removed long-lived tokens that had been sitting in repository secrets for years. If you must use a token (for example, publishing to a private index), prefer uv publish --token $PYPI_TOKEN with a project-scoped token and set it as an environment secret, not a repository secret.
What to check before you publish
Before the first publish for any package, I verify five things: requires-python is not overly permissive (don’t claim 3.8 support if you only test 3.11+), readme points to a file that is included in the sdist, license is set, [project.urls] is populated, and the wheel does not bundle tests or private fixtures. Hatchling respects [tool.hatch.build.targets.wheel.packages] and [tool.hatch.build.targets.sdist.exclude], so you can be explicit. The Python Documentation on package metadata describes how these fields render on PyPI — missing or malformed metadata is one of the most common reasons a first publish looks broken even though the upload succeeded.
Finally, treat publishing as a separate job from testing. Build once, test the artifact, then publish the same artifact. uv build plus uv publish keeps that pipeline simple without needing Poetry, Flit, or Twine as separate tools.
Frequently Asked Questions
Should I check in uv.lock for a library or only for an application?
Check it in for applications and services — it guarantees every deploy and every developer uses the same resolved graph. For libraries, committing uv.lock is still useful for CI reproducibility, but it does not affect consumers. Consumers resolve against your dependencies ranges, not your lock file, so keep your ranges honest and test them with uv lock --upgrade periodically.
Can uv replace Poetry entirely, or do I need to migrate gradually?
It can replace Poetry for most projects. uv reads [project] metadata natively and supports [dependency-groups] and [tool.uv] overrides. If you have a Poetry project, you can migrate by exporting dependencies to pyproject.toml with poetry export or by letting uv import them, then removing poetry.lock after verifying uv lock resolves cleanly. I usually do this in a single PR and keep poetry.lock for one release as a reference.
How do I handle Python version pinning with requires-python and uv?
Set requires-python = ">=3.11" (or your minimum supported version) in [project] and pin the exact interpreter for local development with .python-version or uv python pin 3.11. uv venv --python 3.11 and uv sync will then enforce consistency. In CI, test the matrix you claim to support — claiming 3.9-3.12 support without testing 3.9 is how subtle syntax or stdlib errors reach users.
What goes in [project.optional-dependencies] vs [dependency-groups]?
Use [project.optional-dependencies] for extras a user might install, like pip install yourpkg[excel] that pulls in openpyxl. Use [dependency-groups] for local-only needs like linters, type checkers, and test runners that are not part of the published package. In my experience, this separation keeps your wheel small and your contributor setup complete with a single uv sync --all-groups.