Build, test, type-check, version, package, and publish production Python libraries to PyPI. Use this skill when creating a pip-installable SDK, CLI, plugin, or utility; choosing `src/` vs flat layout; selecting setuptools, hatchling, flit, or poetry; configuring pyproject.toml, py.typed, Ruff, mypy, pre-commit, GitHub Actions, TestPyPI, Trusted Publishing, setuptools_scm, PEP 440, SemVer, or release governance.
Take a battle-tested, community-ready, end-to-end (to-end) Python library, SDK, CLI, plugin, or utility request, transform it into a modern PyPA package with structure, backend, versioning, typing, quality, CI, and publishing decisions, and output the files and release steps needed for a production-grade PyPI release.
Follow the decision trees in order before writing code. This skill applies to utility libraries, SDKs, CLI tools, framework plugins, and data libraries.
When to invoke
"Create a Python package I can publish to PyPI."
"Build a pip-installable SDK with pyproject.toml."
"Choose setuptools_scm, hatchling, flit, or poetry for this library."
"Set up py.typed, Ruff, mypy, pre-commit, and GitHub Actions."
"Publish this package with Trusted Publishing or TestPyPI."
Scaffold script: run python skills/python-pypi-package-builder/scripts/scaffold.py --name your-package-name
to generate the entire directory layout, stub files, and pyproject.toml in one command.
Trigger details
Load this skill whenever the user wants to:
Create, scaffold, or publish a Python package or library to PyPI
Build a pip-installable SDK, utility, CLI tool, or framework extension
Set up pyproject.toml, linting, mypy, pre-commit, or GitHub Actions for a Python project
Understand versioning (setuptools_scm, PEP 440, semver, static versioning)
Publish to PyPI using Trusted Publishing (OIDC) or API tokens
Refactor an existing package to follow modern Python packaging standards
Add type hints, protocols, ABCs, or dataclasses to a Python library
Apply OOP/SOLID design patterns to a Python package
Choose between build backends (setuptools, hatchling, flit, poetry)
Also trigger for phrases like: "build a Python SDK", "publish my library", "set up PyPI CI",
"create a pip package", "how do I publish to PyPI", "pyproject.toml help", "PEP 561 typed",
"setuptools_scm version", "semver Python", "PEP 440", "git tag release", "Trusted Publishing".
Package type decision
Identify what the user is building before writing any code. Each type has distinct patterns.
Decision Table
Type
Core Pattern
Entry Point
Key Deps
Example Packages
Utility library
Module of pure functions + helpers
Import API only
Minimal
arrow, humanize, boltons, more-itertools
API client / SDK
Class with methods, auth, retry logic
Import API only
httpx or requests
boto3, stripe-python, openai
CLI tool
Command functions + argument parser
[project.scripts] or [project.entry-points]
click or typer
black, ruff, httpie, rich
Framework plugin
Plugin class, hook registration
[project.entry-points."framework.plugin"]
Framework dep
pytest-*, django-*, flask-*
Data processing library
Classes + functional pipeline
Import API only
Optional: numpy, pandas
pydantic, marshmallow, cerberus
Mixed / generic
Combination of above
Varies
Varies
Many real-world packages
Decision Rule: Ask the user if unclear. A package can combine types (e.g., SDK with a CLI
entry point) — use the primary type for structural decisions and add secondary type patterns on top.
For implementation patterns of each type, see references/library-patterns.md.
Package Naming Rules
PyPI name: all lowercase, hyphens — my-python-library
Avoid shadowing popular packages (verify pip install <name> fails first)
Folder structure decision
Decision Tree
Does the package have 5+ internal modules OR multiple contributors OR complex sub-packages?
├── YES → Use src/ layout
│ Reason: prevents accidental import of uninstalled code during development;
│ separates source from project root files; PyPA-recommended for large projects.
│
├── NO → Is it a single-module, focused package (e.g., one file + helpers)?
│ ├── YES → Use flat layout
│ └── NO (medium complexity) → Use flat layout, migrate to src/ if it grows
│
└── Is it multiple related packages under one namespace (e.g., myorg.http, myorg.db)?
└── YES → Use namespace/monorepo layout
Quick Rule Summary
Situation
Use
New project, unknown future size
src/ layout (safest default)
Single-purpose, 1–4 modules
Flat layout
Large library, many contributors
src/ layout
Multiple packages in one repo
Namespace / monorepo
Migrating old flat project
Keep flat; migrate to src/ at next major version
Build backend decision
Decision Tree
Does the user need version derived automatically from git tags?
├── YES → Use setuptools + setuptools_scm
│ (git tag v1.0.0 → that IS your release workflow)
│
└── NO → Does the user want an all-in-one tool (deps + build + publish)?
├── YES → Use poetry (v2+ supports standard [project] table)
│
└── NO → Is the package pure Python with no C extensions?
├── YES, minimal config preferred → Use flit
│ (zero config, auto-discovers version from __version__)
│
└── YES, modern & fast preferred → Use hatchling
(zero-config, plugin system, no setup.py needed)
Does the package have C/Cython/Fortran extensions?
└── YES → MUST use setuptools (only backend with full native extension support)
Backend Comparison
Backend
Version source
Config
C extensions
Best for
setuptools + setuptools_scm
git tags (automatic)
pyproject.toml + optional setup.py shim
Yes
Projects with git-tag releases; any complexity
hatchling
manual or plugin
pyproject.toml only
No
New pure-Python projects; fast, modern
flit
__version__ in __init__.py
pyproject.toml only
No
Very simple, single-module packages
poetry
pyproject.toml field
pyproject.toml only
No
Teams wanting integrated dep management
For all four complete pyproject.toml templates, see references/pyproject-toml.md.
PyPA packaging flow
This is the canonical end-to-end flow from source code to user install.
Every step must be understood before publishing.
1. SOURCE TREE
Your code in version control (git)
└── pyproject.toml describes metadata + build system
2. BUILD
python -m build
└── Produces two artifacts in dist/:
├── *.tar.gz → source distribution (sdist)
└── *.whl → built distribution (wheel) — preferred by pip
3. VALIDATE
twine check dist/*
└── Checks metadata, README rendering, and PyPI compatibility
4. TEST PUBLISH (first release only)
twine upload --repository testpypi dist/*
└── Verify: pip install --index-url https://test.pypi.org/simple/ your-package
5. PUBLISH
twine upload dist/* ← manual fallback
OR GitHub Actions publish.yml ← recommended (Trusted Publishing / OIDC)
6. USER INSTALL
pip install your-package
pip install "your-package[extra]"
Key PyPA Concepts
Concept
What it means
sdist
Source distribution — your source + metadata; used when no wheel is available
wheel (.whl)
Pre-built binary — pip extracts directly into site-packages; no build step
PEP 517/518
Standard build system interface via pyproject.toml [build-system] table
PEP 621
Standard [project] table in pyproject.toml; all modern backends support it
PEP 639
license key as SPDX string (e.g., "MIT", "Apache-2.0") — not {text = "MIT"}
PEP 561
py.typed empty marker file — tells mypy/IDEs this package ships type information
For complete CI workflow and publishing setup, see references/ci-publishing.md.
Project structure templates
A. src/ Layout (Recommended default for new projects)
Each sub-package has its own pyproject.toml. They share the your_org namespace via PEP 420
implicit namespace packages (no __init__.py in the namespace root).
MAJOR.MINOR.PATCH
MAJOR: Breaking API change (remove/rename public function/class/arg)
MINOR: New feature, fully backward-compatible
PATCH: Bug fix, no API change
Dynamic versioning with setuptools_scm (recommended for git-tag workflows)
# How it works:
git tag v1.0.0 → installed version = 1.0.0
git tag v1.1.0 → installed version = 1.1.0
(commits after tag) → version = 1.1.0.post1 (suffix stripped for PyPI)
# In code — NEVER hardcode when using setuptools_scm:
from importlib.metadata import version, PackageNotFoundError
try:
__version__ = version("your-package")
except PackageNotFoundError:
__version__ = "0.0.0-dev" # Fallback for uninstalled dev checkouts
Critical: always set fetch-depth: 0 in every CI checkout step. Without full git history,
setuptools_scm cannot find tags and the build version silently falls back to 0.0.0+dev.
# your_package/__init__.py
__version__ = "1.0.0" # Update this before every release
Version specifier best practices for dependencies
# In [project] dependencies:
"httpx>=0.24" # Minimum version — PREFERRED for libraries
"httpx>=0.24,<1.0" # Upper bound only when a known breaking change exists
"httpx==0.27.0" # Pin exactly ONLY in applications, NOT libraries
# NEVER do this in a library — it breaks dependency resolution for users:
# "httpx~=0.24.0" # Too tight
# "httpx==0.27.*" # Fragile
Version bump → release flow
# 1. Update CHANGELOG.md — move [Unreleased] entries to [x.y.z] - YYYY-MM-DD
# 2. Commit the changelog
git add CHANGELOG.md
git commit -m "chore: prepare release vX.Y.Z"
# 3. Tag and push — this triggers publish.yml automatically
git tag vX.Y.Z
git push origin main --tags
# 4. Monitor GitHub Actions → verify on https://pypi.org/project/your-package/
For complete pyproject.toml templates for all four backends, see references/pyproject-toml.md.
Progressive disclosure and bundled resources
After understanding decisions and structure:
Set up pyproject.toml → references/pyproject-toml.md
All four backend templates (setuptools+scm, hatchling, flit, poetry), full tool configs,
py.typed setup, versioning config.
Write your library code → references/library-patterns.md
OOP/SOLID principles, type hints (PEP 484/526/544/561), core class design, factory functions,
__init__.py, plugin/backend pattern, CLI entry point.
Set up CI/CD and publish → references/ci-publishing.mdci.yml, publish.yml with Trusted Publishing (OIDC, no API tokens), CHANGELOG format,
release checklist.
Polish for community/OSS → references/community-docs.md
README sections, docstring format, CONTRIBUTING, SECURITY, issue templates, anti-patterns
table, and master release checklist.
Design backends, config, transport, CLI → references/architecture-patterns.md
Backend system (plugin/strategy pattern), Settings dataclass, HTTP transport layer,
CLI with click/typer, backend injection rules.
Choose and implement a versioning strategy → references/versioning-strategy.md
PEP 440 canonical forms, SemVer rules, pre-release identifiers, setuptools_scm deep-dive,
flit static versioning, decision engine (DEFAULT/BEGINNER/MINIMAL).
Govern releases and secure the publish pipeline → references/release-governance.md
Branch strategy, branch protection rules, OIDC Trusted Publishing setup, tag author
validation in CI, tag format enforcement, full governed publish.yml.
1---2name: python-pypi-package-builder3description: Build, test, type-check, version, package, and publish production Python libraries to PyPI. Use this skill when creating a pip-installable SDK, CLI, plugin, or utility; choosing `src/` vs flat layout; selecting setuptools, hatchling, flit, or poetry; configuring pyproject.toml, py.typed, Ruff, mypy, pre-commit, GitHub Actions, TestPyPI, Trusted Publishing, setuptools_scm, PEP 440, SemVer, or release governance.4---56<!-- Generated from harness/github-copilot/skills/python-pypi-package-builder/SKILL.md by harness/claude-code/scripts/convert_from_copilot.py. Edit the source, not this file. -->78# Python PyPI package builder910Take a battle-tested, community-ready, end-to-end (`to-end`) Python library, SDK, CLI, plugin, or utility request, transform it into a modern PyPA package with structure, backend, versioning, typing, quality, CI, and publishing decisions, and output the files and release steps needed for a production-grade PyPI release.1112Follow the decision trees in order before writing code. This skill applies to utility libraries, SDKs, CLI tools, framework plugins, and data libraries.1314## When to invoke1516- "Create a Python package I can publish to PyPI."17- "Build a pip-installable SDK with pyproject.toml."18- "Choose setuptools_scm, hatchling, flit, or poetry for this library."19- "Set up py.typed, Ruff, mypy, pre-commit, and GitHub Actions."20- "Publish this package with Trusted Publishing or TestPyPI."2122## Decision map2324| Section in this file | What it covers |25|---|---|26| [1. Skill Trigger](#1-skill-trigger) | When to load this skill |27| [2. Package Type Decision](#2-package-type-decision) | Identify what you are building |28| [3. Folder Structure Decision](#3-folder-structure-decision) | src/ vs flat vs monorepo |29| [4. Build Backend Decision](#4-build-backend-decision) | setuptools / hatchling / flit / poetry |30| [5. PyPA Packaging Flow](#5-pypa-packaging-flow) | The canonical publish pipeline |31| [6. Project Structure Templates](#6-project-structure-templates) | Full layouts for every option |32| [7. Versioning Strategy](#7-versioning-strategy) | PEP 440, semver, dynamic vs static |3334| Reference file | What it covers |35|---|---|36| `references/pyproject-toml.md` | All four backend templates, `setuptools_scm`, `py.typed`, tool configs |37| `references/library-patterns.md` | OOP/SOLID, type hints, core class design, factory, protocols, CLI |38| `references/testing-quality.md` | `conftest.py`, unit/backend/async tests, ruff/mypy/pre-commit |39| `references/ci-publishing.md` | `ci.yml`, `publish.yml`, Trusted Publishing, TestPyPI, CHANGELOG, release checklist |40| `references/community-docs.md` | README, docstrings, CONTRIBUTING, SECURITY, anti-patterns, master checklist |41| `references/architecture-patterns.md` | Backend system (plugin/strategy), config layer, transport layer, CLI, backend injection |42| `references/versioning-strategy.md` | PEP 440, SemVer, pre-release, setuptools_scm deep-dive, flit static, decision engine |43| `references/release-governance.md` | Branch strategy, branch protection, OIDC, tag author validation, prevent invalid tags |44| `references/tooling-ruff.md` | Ruff-only setup (replaces black/isort), mypy config, pre-commit, asyncio_mode=auto |4546**Scaffold script:** run `python skills/python-pypi-package-builder/scripts/scaffold.py --name your-package-name`47to generate the entire directory layout, stub files, and `pyproject.toml` in one command.4849---5051## Trigger details5253Load this skill whenever the user wants to:5455- Create, scaffold, or publish a Python package or library to PyPI56- Build a pip-installable SDK, utility, CLI tool, or framework extension57- Set up `pyproject.toml`, linting, mypy, pre-commit, or GitHub Actions for a Python project58- Understand versioning (`setuptools_scm`, PEP 440, semver, static versioning)59- Understand PyPA specs: `py.typed`, `MANIFEST.in`, `RECORD`, classifiers60- Publish to PyPI using Trusted Publishing (OIDC) or API tokens61- Refactor an existing package to follow modern Python packaging standards62- Add type hints, protocols, ABCs, or dataclasses to a Python library63- Apply OOP/SOLID design patterns to a Python package64- Choose between build backends (setuptools, hatchling, flit, poetry)6566**Also trigger for phrases like:** "build a Python SDK", "publish my library", "set up PyPI CI",67"create a pip package", "how do I publish to PyPI", "pyproject.toml help", "PEP 561 typed",68"setuptools_scm version", "semver Python", "PEP 440", "git tag release", "Trusted Publishing".6970---7172## Package type decision7374Identify what the user is building **before** writing any code. Each type has distinct patterns.7576### Decision Table7778| Type | Core Pattern | Entry Point | Key Deps | Example Packages |79|---|---|---|---|---|80| **Utility library** | Module of pure functions + helpers | Import API only | Minimal | `arrow`, `humanize`, `boltons`, `more-itertools` |81| **API client / SDK** | Class with methods, auth, retry logic | Import API only | `httpx` or `requests` | `boto3`, `stripe-python`, `openai` |82| **CLI tool** | Command functions + argument parser | `[project.scripts]` or `[project.entry-points]` | `click` or `typer` | `black`, `ruff`, `httpie`, `rich` |83| **Framework plugin** | Plugin class, hook registration | `[project.entry-points."framework.plugin"]` | Framework dep | `pytest-*`, `django-*`, `flask-*` |84| **Data processing library** | Classes + functional pipeline | Import API only | Optional: `numpy`, `pandas` | `pydantic`, `marshmallow`, `cerberus` |85| **Mixed / generic** | Combination of above | Varies | Varies | Many real-world packages |8687**Decision Rule:** Ask the user if unclear. A package can combine types (e.g., SDK with a CLI88entry point) — use the primary type for structural decisions and add secondary type patterns on top.8990For implementation patterns of each type, see `references/library-patterns.md`.9192### Package Naming Rules9394- PyPI name: all lowercase, hyphens — `my-python-library`95- Python import name: underscores — `my_python_library`96- Check availability: https://pypi.org/search/ before starting97- Avoid shadowing popular packages (verify `pip install <name>` fails first)9899---100101## Folder structure decision102103### Decision Tree104105```106Does the package have 5+ internal modules OR multiple contributors OR complex sub-packages?107├── YES → Use src/ layout108│ Reason: prevents accidental import of uninstalled code during development;109│ separates source from project root files; PyPA-recommended for large projects.110│111├── NO → Is it a single-module, focused package (e.g., one file + helpers)?112│ ├── YES → Use flat layout113│ └── NO (medium complexity) → Use flat layout, migrate to src/ if it grows114│115└── Is it multiple related packages under one namespace (e.g., myorg.http, myorg.db)?116 └── YES → Use namespace/monorepo layout117```118119### Quick Rule Summary120121| Situation | Use |122|---|---|123| New project, unknown future size | `src/` layout (safest default) |124| Single-purpose, 1–4 modules | Flat layout |125| Large library, many contributors | `src/` layout |126| Multiple packages in one repo | Namespace / monorepo |127| Migrating old flat project | Keep flat; migrate to `src/` at next major version |128129---130131## Build backend decision132133### Decision Tree134135```136Does the user need version derived automatically from git tags?137├── YES → Use setuptools + setuptools_scm138│ (git tag v1.0.0 → that IS your release workflow)139│140└── NO → Does the user want an all-in-one tool (deps + build + publish)?141 ├── YES → Use poetry (v2+ supports standard [project] table)142 │143 └── NO → Is the package pure Python with no C extensions?144 ├── YES, minimal config preferred → Use flit145 │ (zero config, auto-discovers version from __version__)146 │147 └── YES, modern & fast preferred → Use hatchling148 (zero-config, plugin system, no setup.py needed)149150Does the package have C/Cython/Fortran extensions?151└── YES → MUST use setuptools (only backend with full native extension support)152```153154### Backend Comparison155156| Backend | Version source | Config | C extensions | Best for |157|---|---|---|---|---|158| `setuptools` + `setuptools_scm` | git tags (automatic) | `pyproject.toml` + optional `setup.py` shim | Yes | Projects with git-tag releases; any complexity |159| `hatchling` | manual or plugin | `pyproject.toml` only | No | New pure-Python projects; fast, modern |160| `flit` | `__version__` in `__init__.py` | `pyproject.toml` only | No | Very simple, single-module packages |161| `poetry` | `pyproject.toml` field | `pyproject.toml` only | No | Teams wanting integrated dep management |162163For all four complete `pyproject.toml` templates, see `references/pyproject-toml.md`.164165---166167## PyPA packaging flow168169This is the canonical end-to-end flow from source code to user install.170**Every step must be understood before publishing.**171172```1731. SOURCE TREE174 Your code in version control (git)175 └── pyproject.toml describes metadata + build system1761772. BUILD178 python -m build179 └── Produces two artifacts in dist/:180 ├── *.tar.gz → source distribution (sdist)181 └── *.whl → built distribution (wheel) — preferred by pip1821833. VALIDATE184 twine check dist/*185 └── Checks metadata, README rendering, and PyPI compatibility1861874. TEST PUBLISH (first release only)188 twine upload --repository testpypi dist/*189 └── Verify: pip install --index-url https://test.pypi.org/simple/ your-package1901915. PUBLISH192 twine upload dist/* ← manual fallback193 OR GitHub Actions publish.yml ← recommended (Trusted Publishing / OIDC)1941956. USER INSTALL196 pip install your-package197 pip install "your-package[extra]"198```199200### Key PyPA Concepts201202| Concept | What it means |203|---|---|204| **sdist** | Source distribution — your source + metadata; used when no wheel is available |205| **wheel (.whl)** | Pre-built binary — pip extracts directly into site-packages; no build step |206| **PEP 517/518** | Standard build system interface via `pyproject.toml [build-system]` table |207| **PEP 621** | Standard `[project]` table in `pyproject.toml`; all modern backends support it |208| **PEP 639** | `license` key as SPDX string (e.g., `"MIT"`, `"Apache-2.0"`) — not `{text = "MIT"}` |209| **PEP 561** | `py.typed` empty marker file — tells mypy/IDEs this package ships type information |210211For complete CI workflow and publishing setup, see `references/ci-publishing.md`.212213---214215## Project structure templates216217### A. src/ Layout (Recommended default for new projects)218219```220your-package/221├── src/222│ └── your_package/223│ ├── __init__.py # Public API: __all__, __version__224│ ├── py.typed # PEP 561 marker — EMPTY FILE225│ ├── core.py # Primary implementation226│ ├── client.py # (API client type) or remove227│ ├── cli.py # (CLI type) click/typer commands, or remove228│ ├── config.py # Settings / configuration dataclass229│ ├── exceptions.py # Custom exception hierarchy230│ ├── models.py # Data classes, Pydantic models, TypedDicts231│ ├── utils.py # Internal helpers (prefix _utils if private)232│ ├── types.py # Shared type aliases and TypeVars233│ └── backends/ # (Plugin pattern) — remove if not needed234│ ├── __init__.py # Protocol / ABC interface definition235│ ├── memory.py # Default zero-dep implementation236│ └── redis.py # Optional heavy implementation237├── tests/238│ ├── __init__.py239│ ├── conftest.py # Shared fixtures240│ ├── unit/241│ │ ├── __init__.py242│ │ ├── test_core.py243│ │ ├── test_config.py244│ │ └── test_models.py245│ ├── integration/246│ │ ├── __init__.py247│ │ └── test_backends.py248│ └── e2e/ # Optional: end-to-end tests249│ └── __init__.py250├── docs/ # Optional: mkdocs or sphinx251├── scripts/252│ └── scaffold.py253├── .github/254│ ├── workflows/255│ │ ├── ci.yml256│ │ └── publish.yml257│ └── ISSUE_TEMPLATE/258│ ├── bug_report.md259│ └── feature_request.md260├── .pre-commit-config.yaml261├── pyproject.toml262├── CHANGELOG.md263├── CONTRIBUTING.md264├── SECURITY.md265├── LICENSE266├── README.md267└── .gitignore268```269270### B. Flat Layout (Small / focused packages)271272```273your-package/274├── your_package/ # ← at root, not inside src/275│ ├── __init__.py276│ ├── py.typed277│ └── ... (same internal structure)278├── tests/279└── ... (same top-level files)280```281282### C. Namespace / Monorepo Layout (Multiple related packages)283284```285your-org/286├── packages/287│ ├── your-org-core/288│ │ ├── src/your_org/core/289│ │ └── pyproject.toml290│ ├── your-org-http/291│ │ ├── src/your_org/http/292│ │ └── pyproject.toml293│ └── your-org-cli/294│ ├── src/your_org/cli/295│ └── pyproject.toml296├── .github/workflows/297└── README.md298```299300Each sub-package has its own `pyproject.toml`. They share the `your_org` namespace via PEP 420301implicit namespace packages (no `__init__.py` in the namespace root).302303### Internal Module Guidelines304305| File | Purpose | When to include |306|---|---|---|307| `__init__.py` | Public API surface; re-exports; `__version__` | Always |308| `py.typed` | PEP 561 typed-package marker (empty) | Always |309| `core.py` | Primary class / main logic | Always |310| `config.py` | Settings dataclass or Pydantic model | When configurable |311| `exceptions.py` | Exception hierarchy (`YourBaseError` → specifics) | Always |312| `models.py` | Data models / DTOs / TypedDicts | When data-heavy |313| `utils.py` | Internal helpers (not part of public API) | As needed |314| `types.py` | Shared `TypeVar`, `TypeAlias`, `Protocol` definitions | When complex typing |315| `cli.py` | CLI entry points (click/typer) | CLI type only |316| `backends/` | Plugin/strategy pattern | When swappable implementations |317| `_compat.py` | Python version compatibility shims | When 3.9–3.13 compat needed |318319---320321## Versioning strategy322323### PEP 440 — The Standard324325```326Canonical form: N[.N]+[{a|b|rc}N][.postN][.devN]327328Examples:329 1.0.0 Stable release330 1.0.0a1 Alpha (pre-release)331 1.0.0b2 Beta332 1.0.0rc1 Release candidate333 1.0.0.post1 Post-release (e.g., packaging fix only)334 1.0.0.dev1 Development snapshot (not for PyPI)335```336337### Semantic Versioning (recommended)338339```340MAJOR.MINOR.PATCH341342MAJOR: Breaking API change (remove/rename public function/class/arg)343MINOR: New feature, fully backward-compatible344PATCH: Bug fix, no API change345```346347### Dynamic versioning with setuptools_scm (recommended for git-tag workflows)348349```bash350# How it works:351git tag v1.0.0 → installed version = 1.0.0352git tag v1.1.0 → installed version = 1.1.0353(commits after tag) → version = 1.1.0.post1 (suffix stripped for PyPI)354355# In code — NEVER hardcode when using setuptools_scm:356from importlib.metadata import version, PackageNotFoundError357try:358 __version__ = version("your-package")359except PackageNotFoundError:360 __version__ = "0.0.0-dev" # Fallback for uninstalled dev checkouts361```362363Required `pyproject.toml` config:364```toml365[tool.setuptools_scm]366version_scheme = "post-release"367local_scheme = "no-local-version" # Prevents +g<hash> from breaking PyPI uploads368```369370**Critical:** always set `fetch-depth: 0` in every CI checkout step. Without full git history,371`setuptools_scm` cannot find tags and the build version silently falls back to `0.0.0+dev`.372373### Static versioning (flit, hatchling manual, poetry)374375```python376# your_package/__init__.py377__version__ = "1.0.0" # Update this before every release378```379380### Version specifier best practices for dependencies381382```toml383# In [project] dependencies:384"httpx>=0.24" # Minimum version — PREFERRED for libraries385"httpx>=0.24,<1.0" # Upper bound only when a known breaking change exists386"httpx==0.27.0" # Pin exactly ONLY in applications, NOT libraries387388# NEVER do this in a library — it breaks dependency resolution for users:389# "httpx~=0.24.0" # Too tight390# "httpx==0.27.*" # Fragile391```392393### Version bump → release flow394395```bash396# 1. Update CHANGELOG.md — move [Unreleased] entries to [x.y.z] - YYYY-MM-DD397# 2. Commit the changelog398git add CHANGELOG.md399git commit -m "chore: prepare release vX.Y.Z"400# 3. Tag and push — this triggers publish.yml automatically401git tag vX.Y.Z402git push origin main --tags403# 4. Monitor GitHub Actions → verify on https://pypi.org/project/your-package/404```405406For complete pyproject.toml templates for all four backends, see `references/pyproject-toml.md`.407408---409410## Progressive disclosure and bundled resources411412After understanding decisions and structure:4134141. **Set up `pyproject.toml`** → `references/pyproject-toml.md`415 All four backend templates (setuptools+scm, hatchling, flit, poetry), full tool configs,416 `py.typed` setup, versioning config.4174182. **Write your library code** → `references/library-patterns.md`419 OOP/SOLID principles, type hints (PEP 484/526/544/561), core class design, factory functions,420 `__init__.py`, plugin/backend pattern, CLI entry point.4214223. **Add tests and code quality** → `references/testing-quality.md`423 `conftest.py`, unit/backend/async tests, parametrize, ruff/mypy/pre-commit setup.4244254. **Set up CI/CD and publish** → `references/ci-publishing.md`426 `ci.yml`, `publish.yml` with Trusted Publishing (OIDC, no API tokens), CHANGELOG format,427 release checklist.4284295. **Polish for community/OSS** → `references/community-docs.md`430 README sections, docstring format, CONTRIBUTING, SECURITY, issue templates, anti-patterns431 table, and master release checklist.4324336. **Design backends, config, transport, CLI** → `references/architecture-patterns.md`434 Backend system (plugin/strategy pattern), Settings dataclass, HTTP transport layer,435 CLI with click/typer, backend injection rules.4364377. **Choose and implement a versioning strategy** → `references/versioning-strategy.md`438 PEP 440 canonical forms, SemVer rules, pre-release identifiers, setuptools_scm deep-dive,439 flit static versioning, decision engine (DEFAULT/BEGINNER/MINIMAL).4404418. **Govern releases and secure the publish pipeline** → `references/release-governance.md`442 Branch strategy, branch protection rules, OIDC Trusted Publishing setup, tag author443 validation in CI, tag format enforcement, full governed `publish.yml`.4444459. **Simplify tooling with Ruff** → `references/tooling-ruff.md`446 Ruff-only setup replacing black/isort/flake8, mypy config, pre-commit hooks,447 asyncio_mode=auto (remove @pytest.mark.asyncio), migration guide.448## Output template449450```markdown451### Python package build result452453**Status:** scaffolded | updated | published | blocked454**Package:** `<pypi-name>` / import name `<import_name>`455**Type:** utility library | API client / SDK | CLI tool | framework plugin | data processing library | mixed456**Layout:** `src/` | flat | namespace / monorepo457**Backend:** `setuptools` + `setuptools_scm` | `hatchling` | `flit` | `poetry`458**Versioning:** PEP 440 / SemVer / static / dynamic git-tag459460**Files created or changed**461- `pyproject.toml`: <backend, metadata, dependencies, tool config>462- `<package>/py.typed`: <present and empty>463- `tests/`: <unit/integration/e2e coverage added>464- `.github/workflows/ci.yml`: <quality gates>465- `.github/workflows/publish.yml`: <Trusted Publishing or manual fallback>466- `README.md`, `CHANGELOG.md`, `CONTRIBUTING.md`, `SECURITY.md`: <status>467468**Commands**469- `python -m build`: pass | fail470- `twine check dist/*`: pass | fail471- `pytest`: pass | fail472- `ruff check .`: pass | fail473- `mypy`: pass | fail474475**Release path**476- TestPyPI: `twine upload --repository testpypi dist/*` then `pip install --index-url https://test.pypi.org/simple/ your-package`477- PyPI: Trusted Publishing workflow or `twine upload dist/*`478```479480## Quality gate481482- [ ] Package type, layout, backend, and versioning choices were made using the decision tables in this skill.483- [ ] PyPI name is lowercase with hyphens, import name uses underscores, and availability was checked at (https://pypi.org/search/).484- [ ] `pyproject.toml` uses PEP 517/518 and PEP 621 metadata, with PEP 639 SPDX `license` syntax.485- [ ] Typed packages include an empty `py.typed` marker for PEP 561 and suitable PEP 484/526/544 hints.486- [ ] Libraries avoid exact dependency pins unless there is a documented compatibility reason.487- [ ] Dynamic `setuptools_scm` projects set `local_scheme = "no-local-version"` and CI checkout uses `fetch-depth: 0`.488- [ ] Build artifacts in `dist/` pass `python -m build` and `twine check dist/*`.489- [ ] Tests, Ruff, mypy, and pre-commit configuration match the selected package complexity.490- [ ] Publishing uses Trusted Publishing / OIDC where possible; API tokens are fallback only and never committed.491- [ ] Release governance covers `CHANGELOG.md`, valid `vX.Y.Z` tags, branch protection, and https://pypi.org/project/your-package/ verification.492- [ ] Bundled references and `scripts/scaffold.py` are used on demand rather than copied blindly.493494## References495496- [PyPI package search](https://pypi.org/search/)497- [TestPyPI simple index](https://test.pypi.org/simple/)498- [Example PyPI project verification URL](https://pypi.org/project/your-package/)
Run npx skillmds@latest add paulasilvatech/python-pypi-package-builder in your terminal (requires Node.js), paste this page's agent-chat prompt into Claude, Cursor, or any MCP-connected agent, or download the SKILL.md file and copy it into your agent's skills directory.
Build, test, type-check, version, package, and publish production Python libraries to PyPI. Use this skill when creating a pip-installable SDK, CLI, plugin, or utility; choosing `src/` vs flat layout; selecting setuptools, hatchling, flit, or poetry; configuring pyproject.toml, py.typed, Ruff, mypy, pre-commit, GitHub Actions, TestPyPI, Trusted Publishing, setuptools_scm, PEP 440, SemVer, or release governance. It is listed under Coding & Dev Tools on SkillMD.
This skill has not completed SkillMD's automated safety review yet. SkillMD never runs a skill's scripts for you; review the SKILL.md before installing.
This skill is tagged as working with Claude Code, Claude.ai, OpenAI Codex. SKILL.md is an open format, so most agents that read a skills directory can load it too.
Yes. Installing skills from SkillMD is free, and the skill stays under its author's original license.
paulasilvatech (@paulasilvatech) published this skill. Their other Agent Skills are listed on their SkillMD profile.