1
---
2
name: python-pypi-package-builder
3
description: 'End-to-end skill for building, testing, linting, versioning, and publishing a production-grade Python library to PyPI. Covers all four build backends (setuptools+setuptools_scm, hatchling, flit, poetry), PEP 440 versioning, semantic versioning, dynamic git-tag versioning, OOP/SOLID design, type hints (PEP 484/526/544/561), Trusted Publishing (OIDC), and the full PyPA packaging flow. Use for: creating Python packages, pip-installable SDKs, CLI tools, framework plugins, pyproject.toml setup, py.typed, setuptools_scm, semver, mypy, pre-commit, GitHub Actions CI/CD, or PyPI publishing.'
4
---
5
6
# Python PyPI Package Builder Skill
7
8
A complete, battle-tested guide for building, testing, linting, versioning, typing, and
9
publishing a production-grade Python library to PyPI — from first commit to community-ready
10
release.
11
12
> **AI Agent Instruction:** Read this entire file before writing a single line of code or
13
> creating any file. Every decision — layout, backend, versioning strategy, patterns, CI —
14
> has a decision rule here. Follow the decision trees in order. This skill applies to any
15
> Python package type (utility, SDK, CLI, plugin, data library). Do not skip sections.
16
17
---
18
19
## Quick Navigation
20
21
| Section in this file | What it covers |
22
|---|---|
23
| [1. Skill Trigger](#1-skill-trigger) | When to load this skill |
24
| [2. Package Type Decision](#2-package-type-decision) | Identify what you are building |
25
| [3. Folder Structure Decision](#3-folder-structure-decision) | src/ vs flat vs monorepo |
26
| [4. Build Backend Decision](#4-build-backend-decision) | setuptools / hatchling / flit / poetry |
27
| [5. PyPA Packaging Flow](#5-pypa-packaging-flow) | The canonical publish pipeline |
28
| [6. Project Structure Templates](#6-project-structure-templates) | Full layouts for every option |
29
| [7. Versioning Strategy](#7-versioning-strategy) | PEP 440, semver, dynamic vs static |
30
31
| Reference file | What it covers |
32
|---|---|
33
| `references/pyproject-toml.md` | All four backend templates, `setuptools_scm`, `py.typed`, tool configs |
34
| `references/library-patterns.md` | OOP/SOLID, type hints, core class design, factory, protocols, CLI |
35
| `references/testing-quality.md` | `conftest.py`, unit/backend/async tests, ruff/mypy/pre-commit |
36
| `references/ci-publishing.md` | `ci.yml`, `publish.yml`, Trusted Publishing, TestPyPI, CHANGELOG, release checklist |
37
| `references/community-docs.md` | README, docstrings, CONTRIBUTING, SECURITY, anti-patterns, master checklist |
38
| `references/architecture-patterns.md` | Backend system (plugin/strategy), config layer, transport layer, CLI, backend injection |
39
| `references/versioning-strategy.md` | PEP 440, SemVer, pre-release, setuptools_scm deep-dive, flit static, decision engine |
40
| `references/release-governance.md` | Branch strategy, branch protection, OIDC, tag author validation, prevent invalid tags |
41
| `references/tooling-ruff.md` | Ruff-only setup (replaces black/isort), mypy config, pre-commit, asyncio_mode=auto |
42
43
**Scaffold script:** run `python skills/python-pypi-package-builder/scripts/scaffold.py --name your-package-name`
44
to generate the entire directory layout, stub files, and `pyproject.toml` in one command.
45
46
---
47
48
## 1. Skill Trigger
49
50
Load this skill whenever the user wants to:
51
52
- Create, scaffold, or publish a Python package or library to PyPI
53
- Build a pip-installable SDK, utility, CLI tool, or framework extension
54
- Set up `pyproject.toml`, linting, mypy, pre-commit, or GitHub Actions for a Python project
55
- Understand versioning (`setuptools_scm`, PEP 440, semver, static versioning)
56
- Understand PyPA specs: `py.typed`, `MANIFEST.in`, `RECORD`, classifiers
57
- Publish to PyPI using Trusted Publishing (OIDC) or API tokens
58
- Refactor an existing package to follow modern Python packaging standards
59
- Add type hints, protocols, ABCs, or dataclasses to a Python library
60
- Apply OOP/SOLID design patterns to a Python package
61
- Choose between build backends (setuptools, hatchling, flit, poetry)
62
63
**Also trigger for phrases like:** "build a Python SDK", "publish my library", "set up PyPI CI",
64
"create a pip package", "how do I publish to PyPI", "pyproject.toml help", "PEP 561 typed",
65
"setuptools_scm version", "semver Python", "PEP 440", "git tag release", "Trusted Publishing".
66
67
---
68
69
## 2. Package Type Decision
70
71
Identify what the user is building **before** writing any code. Each type has distinct patterns.
72
73
### Decision Table
74
75
| Type | Core Pattern | Entry Point | Key Deps | Example Packages |
76
|---|---|---|---|---|
77
| **Utility library** | Module of pure functions + helpers | Import API only | Minimal | `arrow`, `humanize`, `boltons`, `more-itertools` |
78
| **API client / SDK** | Class with methods, auth, retry logic | Import API only | `httpx` or `requests` | `boto3`, `stripe-python`, `openai` |
79
| **CLI tool** | Command functions + argument parser | `[project.scripts]` or `[project.entry-points]` | `click` or `typer` | `black`, `ruff`, `httpie`, `rich` |
80
| **Framework plugin** | Plugin class, hook registration | `[project.entry-points."framework.plugin"]` | Framework dep | `pytest-*`, `django-*`, `flask-*` |
81
| **Data processing library** | Classes + functional pipeline | Import API only | Optional: `numpy`, `pandas` | `pydantic`, `marshmallow`, `cerberus` |
82
| **Mixed / generic** | Combination of above | Varies | Varies | Many real-world packages |
83
84
**Decision Rule:** Ask the user if unclear. A package can combine types (e.g., SDK with a CLI
85
entry point) — use the primary type for structural decisions and add secondary type patterns on top.
86
87
For implementation patterns of each type, see `references/library-patterns.md`.
88
89
### Package Naming Rules
90
91
- PyPI name: all lowercase, hyphens — `my-python-library`
92
- Python import name: underscores — `my_python_library`
93
- Check availability: https://pypi.org/search/ before starting
94
- Avoid shadowing popular packages (verify `pip install <name>` fails first)
95
96
---
97
98
## 3. Folder Structure Decision
99
100
### Decision Tree
101
102
```
103
Does the package have 5+ internal modules OR multiple contributors OR complex sub-packages?
104
├── YES → Use src/ layout
105
│ Reason: prevents accidental import of uninstalled code during development;
106
│ separates source from project root files; PyPA-recommended for large projects.
107
│
108
├── NO → Is it a single-module, focused package (e.g., one file + helpers)?
109
│ ├── YES → Use flat layout
110
│ └── NO (medium complexity) → Use flat layout, migrate to src/ if it grows
111
│
112
└── Is it multiple related packages under one namespace (e.g., myorg.http, myorg.db)?
113
└── YES → Use namespace/monorepo layout
114
```
115
116
### Quick Rule Summary
117
118
| Situation | Use |
119
|---|---|
120
| New project, unknown future size | `src/` layout (safest default) |
121
| Single-purpose, 1–4 modules | Flat layout |
122
| Large library, many contributors | `src/` layout |
123
| Multiple packages in one repo | Namespace / monorepo |
124
| Migrating old flat project | Keep flat; migrate to `src/` at next major version |
125
126
---
127
128
## 4. Build Backend Decision
129
130
### Decision Tree
131
132
```
133
Does the user need version derived automatically from git tags?
134
├── YES → Use setuptools + setuptools_scm
135
│ (git tag v1.0.0 → that IS your release workflow)
136
│
137
└── NO → Does the user want an all-in-one tool (deps + build + publish)?
138
├── YES → Use poetry (v2+ supports standard [project] table)
139
│
140
└── NO → Is the package pure Python with no C extensions?
141
├── YES, minimal config preferred → Use flit
142
│ (zero config, auto-discovers version from __version__)
143
│
144
└── YES, modern & fast preferred → Use hatchling
145
(zero-config, plugin system, no setup.py needed)
146
147
Does the package have C/Cython/Fortran extensions?
148
└── YES → MUST use setuptools (only backend with full native extension support)
149
```
150
151
### Backend Comparison
152
153
| Backend | Version source | Config | C extensions | Best for |
154
|---|---|---|---|---|
155
| `setuptools` + `setuptools_scm` | git tags (automatic) | `pyproject.toml` + optional `setup.py` shim | Yes | Projects with git-tag releases; any complexity |
156
| `hatchling` | manual or plugin | `pyproject.toml` only | No | New pure-Python projects; fast, modern |
157
| `flit` | `__version__` in `__init__.py` | `pyproject.toml` only | No | Very simple, single-module packages |
158
| `poetry` | `pyproject.toml` field | `pyproject.toml` only | No | Teams wanting integrated dep management |
159
160
For all four complete `pyproject.toml` templates, see `references/pyproject-toml.md`.
161
162
---
163
164
## 5. PyPA Packaging Flow
165
166
This is the canonical end-to-end flow from source code to user install.
167
**Every step must be understood before publishing.**
168
169
```
170
1. SOURCE TREE
171
Your code in version control (git)
172
└── pyproject.toml describes metadata + build system
173
174
2. BUILD
175
python -m build
176
└── Produces two artifacts in dist/:
177
├── *.tar.gz → source distribution (sdist)
178
└── *.whl → built distribution (wheel) — preferred by pip
179
180
3. VALIDATE
181
twine check dist/*
182
└── Checks metadata, README rendering, and PyPI compatibility
183
184
4. TEST PUBLISH (first release only)
185
twine upload --repository testpypi dist/*
186
└── Verify: pip install --index-url https://test.pypi.org/simple/ your-package
187
188
5. PUBLISH
189
twine upload dist/* ← manual fallback
190
OR GitHub Actions publish.yml ← recommended (Trusted Publishing / OIDC)
191
192
6. USER INSTALL
193
pip install your-package
194
pip install "your-package[extra]"
195
```
196
197
### Key PyPA Concepts
198
199
| Concept | What it means |
200
|---|---|
201
| **sdist** | Source distribution — your source + metadata; used when no wheel is available |
202
| **wheel (.whl)** | Pre-built binary — pip extracts directly into site-packages; no build step |
203
| **PEP 517/518** | Standard build system interface via `pyproject.toml [build-system]` table |
204
| **PEP 621** | Standard `[project]` table in `pyproject.toml`; all modern backends support it |
205
| **PEP 639** | `license` key as SPDX string (e.g., `"MIT"`, `"Apache-2.0"`) — not `{text = "MIT"}` |
206
| **PEP 561** | `py.typed` empty marker file — tells mypy/IDEs this package ships type information |
207
208
For complete CI workflow and publishing setup, see `references/ci-publishing.md`.
209
210
---
211
212
## 6. Project Structure Templates
213
214
### A. src/ Layout (Recommended default for new projects)
215
216
```
217
your-package/
218
├── src/
219
│ └── your_package/
220
│ ├── __init__.py # Public API: __all__, __version__
221
│ ├── py.typed # PEP 561 marker — EMPTY FILE
222
│ ├── core.py # Primary implementation
223
│ ├── client.py # (API client type) or remove
224
│ ├── cli.py # (CLI type) click/typer commands, or remove
225
│ ├── config.py # Settings / configuration dataclass
226
│ ├── exceptions.py # Custom exception hierarchy
227
│ ├── models.py # Data classes, Pydantic models, TypedDicts
228
│ ├── utils.py # Internal helpers (prefix _utils if private)
229
│ ├── types.py # Shared type aliases and TypeVars
230
│ └── backends/ # (Plugin pattern) — remove if not needed
231
│ ├── __init__.py # Protocol / ABC interface definition
232
│ ├── memory.py # Default zero-dep implementation
233
│ └── redis.py # Optional heavy implementation
234
├── tests/
235
│ ├── __init__.py
236
│ ├── conftest.py # Shared fixtures
237
│ ├── unit/
238
│ │ ├── __init__.py
239
│ │ ├── test_core.py
240
│ │ ├── test_config.py
241
│ │ └── test_models.py
242
│ ├── integration/
243
│ │ ├── __init__.py
244
│ │ └── test_backends.py
245
│ └── e2e/ # Optional: end-to-end tests
246
│ └── __init__.py
247
├── docs/ # Optional: mkdocs or sphinx
248
├── scripts/
249
│ └── scaffold.py
250
├── .github/
251
│ ├── workflows/
252
│ │ ├── ci.yml
253
│ │ └── publish.yml
254
│ └── ISSUE_TEMPLATE/
255
│ ├── bug_report.md
256
│ └── feature_request.md
257
├── .pre-commit-config.yaml
258
├── pyproject.toml
259
├── CHANGELOG.md
260
├── CONTRIBUTING.md
261
├── SECURITY.md
262
├── LICENSE
263
├── README.md
264
└── .gitignore
265
```
266
267
### B. Flat Layout (Small / focused packages)
268
269
```
270
your-package/
271
├── your_package/ # ← at root, not inside src/
272
│ ├── __init__.py
273
│ ├── py.typed
274
│ └── ... (same internal structure)
275
├── tests/
276
└── ... (same top-level files)
277
```
278
279
### C. Namespace / Monorepo Layout (Multiple related packages)
280
281
```
282
your-org/
283
├── packages/
284
│ ├── your-org-core/
285
│ │ ├── src/your_org/core/
286
│ │ └── pyproject.toml
287
│ ├── your-org-http/
288
│ │ ├── src/your_org/http/
289
│ │ └── pyproject.toml
290
│ └── your-org-cli/
291
│ ├── src/your_org/cli/
292
│ └── pyproject.toml
293
├── .github/workflows/
294
└── README.md
295
```
296
297
Each sub-package has its own `pyproject.toml`. They share the `your_org` namespace via PEP 420
298
implicit namespace packages (no `__init__.py` in the namespace root).
299
300
### Internal Module Guidelines
301
302
| File | Purpose | When to include |
303
|---|---|---|
304
| `__init__.py` | Public API surface; re-exports; `__version__` | Always |
305
| `py.typed` | PEP 561 typed-package marker (empty) | Always |
306
| `core.py` | Primary class / main logic | Always |
307
| `config.py` | Settings dataclass or Pydantic model | When configurable |
308
| `exceptions.py` | Exception hierarchy (`YourBaseError` → specifics) | Always |
309
| `models.py` | Data models / DTOs / TypedDicts | When data-heavy |
310
| `utils.py` | Internal helpers (not part of public API) | As needed |
311
| `types.py` | Shared `TypeVar`, `TypeAlias`, `Protocol` definitions | When complex typing |
312
| `cli.py` | CLI entry points (click/typer) | CLI type only |
313
| `backends/` | Plugin/strategy pattern | When swappable implementations |
314
| `_compat.py` | Python version compatibility shims | When 3.9–3.13 compat needed |
315
316
---
317
318
## 7. Versioning Strategy
319
320
### PEP 440 — The Standard
321
322
```
323
Canonical form: N[.N]+[{a|b|rc}N][.postN][.devN]
324
325
Examples:
326
1.0.0 Stable release
327
1.0.0a1 Alpha (pre-release)
328
1.0.0b2 Beta
329
1.0.0rc1 Release candidate
330
1.0.0.post1 Post-release (e.g., packaging fix only)
331
1.0.0.dev1 Development snapshot (not for PyPI)
332
```
333
334
### Semantic Versioning (recommended)
335
336
```
337
MAJOR.MINOR.PATCH
338
339
MAJOR: Breaking API change (remove/rename public function/class/arg)
340
MINOR: New feature, fully backward-compatible
341
PATCH: Bug fix, no API change
342
```
343
344
### Dynamic versioning with setuptools_scm (recommended for git-tag workflows)
345
346
```bash
347
# How it works:
348
git tag v1.0.0 → installed version = 1.0.0
349
git tag v1.1.0 → installed version = 1.1.0
350
(commits after tag) → version = 1.1.0.post1 (suffix stripped for PyPI)
351
352
# In code — NEVER hardcode when using setuptools_scm:
353
from importlib.metadata import version, PackageNotFoundError
354
try:
355
__version__ = version("your-package")
356
except PackageNotFoundError:
357
__version__ = "0.0.0-dev" # Fallback for uninstalled dev checkouts
358
```
359
360
Required `pyproject.toml` config:
361
```toml
362
[tool.setuptools_scm]
363
version_scheme = "post-release"
364
local_scheme = "no-local-version" # Prevents +g<hash> from breaking PyPI uploads
365
```
366
367
**Critical:** always set `fetch-depth: 0` in every CI checkout step. Without full git history,
368
`setuptools_scm` cannot find tags and the build version silently falls back to `0.0.0+dev`.
369
370
### Static versioning (flit, hatchling manual, poetry)
371
372
```python
373
# your_package/__init__.py
374
__version__ = "1.0.0" # Update this before every release
375
```
376
377
### Version specifier best practices for dependencies
378
379
```toml
380
# In [project] dependencies:
381
"httpx>=0.24" # Minimum version — PREFERRED for libraries
382
"httpx>=0.24,<1.0" # Upper bound only when a known breaking change exists
383
"httpx==0.27.0" # Pin exactly ONLY in applications, NOT libraries
384
385
# NEVER do this in a library — it breaks dependency resolution for users:
386
# "httpx~=0.24.0" # Too tight
387
# "httpx==0.27.*" # Fragile
388
```
389
390
### Version bump → release flow
391
392
```bash
393
# 1. Update CHANGELOG.md — move [Unreleased] entries to [x.y.z] - YYYY-MM-DD
394
# 2. Commit the changelog
395
git add CHANGELOG.md
396
git commit -m "chore: prepare release vX.Y.Z"
397
# 3. Tag and push — this triggers publish.yml automatically
398
git tag vX.Y.Z
399
git push origin main --tags
400
# 4. Monitor GitHub Actions → verify on https://pypi.org/project/your-package/
401
```
402
403
For complete pyproject.toml templates for all four backends, see `references/pyproject-toml.md`.
404
405
---
406
407
## Where to Go Next
408
409
After understanding decisions and structure:
410
411
1. **Set up `pyproject.toml`** → `references/pyproject-toml.md`
412
All four backend templates (setuptools+scm, hatchling, flit, poetry), full tool configs,
413
`py.typed` setup, versioning config.
414
415
2. **Write your library code** → `references/library-patterns.md`
416
OOP/SOLID principles, type hints (PEP 484/526/544/561), core class design, factory functions,
417
`__init__.py`, plugin/backend pattern, CLI entry point.
418
419
3. **Add tests and code quality** → `references/testing-quality.md`
420
`conftest.py`, unit/backend/async tests, parametrize, ruff/mypy/pre-commit setup.
421
422
4. **Set up CI/CD and publish** → `references/ci-publishing.md`
423
`ci.yml`, `publish.yml` with Trusted Publishing (OIDC, no API tokens), CHANGELOG format,
424
release checklist.
425
426
5. **Polish for community/OSS** → `references/community-docs.md`
427
README sections, docstring format, CONTRIBUTING, SECURITY, issue templates, anti-patterns
428
table, and master release checklist.
429
430
6. **Design backends, config, transport, CLI** → `references/architecture-patterns.md`
431
Backend system (plugin/strategy pattern), Settings dataclass, HTTP transport layer,
432
CLI with click/typer, backend injection rules.
433
434
7. **Choose and implement a versioning strategy** → `references/versioning-strategy.md`
435
PEP 440 canonical forms, SemVer rules, pre-release identifiers, setuptools_scm deep-dive,
436
flit static versioning, decision engine (DEFAULT/BEGINNER/MINIMAL).
437
438
8. **Govern releases and secure the publish pipeline** → `references/release-governance.md`
439
Branch strategy, branch protection rules, OIDC Trusted Publishing setup, tag author
440
validation in CI, tag format enforcement, full governed `publish.yml`.
441
442
9. **Simplify tooling with Ruff** → `references/tooling-ruff.md`
443
Ruff-only setup replacing black/isort/flake8, mypy config, pre-commit hooks,
444
asyncio_mode=auto (remove @pytest.mark.asyncio), migration guide.
445