Python Pypi Package Builder
GitHubOfficialFirst committed by Dhruvpatel004Distributed by GitHub
- Skill
- Workflow
- Software development
- MIT
- Low risk
- Has scripts
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides an end-to-end framework for the entire Python packaging lifecycle. It covers selecting build backends (setuptools, hatchling, flit, poetry), configuring project structures, implementing robust versioning strategies, and setting up automated CI/CD pipelines. It emphasizes modern standards including PEP 440, PEP 561 type hints, and Trusted Publishing for secure PyPI releases.
What it does
- Generates complete project directory layouts with a single command.
- Configures pyproject.toml for various build backends and dependency management.
- Implements automated versioning using git tags via setuptools_scm.
- Sets up GitHub Actions for automated linting, testing, and PyPI publishing.
- Provides patterns for SOLID design, type hinting, and plugin architectures.
- Guides the user through the PyPA packaging flow from local build to release.
When to use it
- When starting a new Python library, SDK, or CLI tool from scratch.
- When refactoring an existing project to follow modern packaging standards.
- When you need to set up automated CI/CD and PyPI publishing pipelines.
- When you need guidance on choosing the right build backend for your project requirements.
Advantages
- Standardizes project structure and configuration across different libraries.
- Reduces manual overhead in versioning and release management.
- Ensures high code quality through integrated linting, typing, and testing.
- Promotes secure publishing practices using OIDC Trusted Publishing.
Usage examples
- “I want to start a new Python SDK project. How should I structure it?”
- The agent will guide you through selecting the src/ layout, choosing a build backend, and using the scaffold script to generate the initial files.
- “How do I set up my Python library to publish to PyPI automatically?”
- The agent will provide the necessary GitHub Actions configuration for Trusted Publishing and explain the required git-tagging release workflow.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/github/python-pypi-package-builder/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip python-pypi-package-builder.zip -d .agents/skills
Documentation by Dhruvpatel004
Python PyPI Package Builder Skill
A complete, battle-tested guide for building, testing, linting, versioning, typing, and publishing a production-grade Python library to PyPI — from first commit to community-ready release.
AI Agent Instruction: Read this entire file before writing a single line of code or creating any file. Every decision — layout, backend, versioning strategy, patterns, CI — has a decision rule here. Follow the decision trees in order. This skill applies to any Python package type (utility, SDK, CLI, plugin, data library). Do not skip sections.
Quick Navigation
| Section in this file | What it covers |
|---|---|
| 1. Skill Trigger | When to load this skill |
| 2. Package Type Decision | Identify what you are building |
| 3. Folder Structure Decision | src/ vs flat vs monorepo |
| 4. Build Backend Decision | setuptools / hatchling / flit / poetry |
| 5. PyPA Packaging Flow | The canonical publish pipeline |
| 6. Project Structure Templates | Full layouts for every option |
| 7. Versioning Strategy | PEP 440, semver, dynamic vs static |
| Reference file | What it covers |
|---|---|
references/pyproject-toml.md | All four backend templates, setuptools_scm, py.typed, tool configs |
references/library-patterns.md | OOP/SOLID, type hints, core class design, factory, protocols, CLI |
references/testing-quality.md | conftest.py, unit/backend/async tests, ruff/mypy/pre-commit |
references/ci-publishing.md | ci.yml, publish.yml, Trusted Publishing, TestPyPI, CHANGELOG, release checklist |
references/community-docs.md | README, docstrings, CONTRIBUTING, SECURITY, anti-patterns, master checklist |
references/architecture-patterns.md | Backend system (plugin/strategy), config layer, transport layer, CLI, backend injection |
references/versioning-strategy.md | PEP 440, SemVer, pre-release, setuptools_scm deep-dive, flit static, decision engine |
references/release-governance.md | Branch strategy, branch protection, OIDC, tag author validation, prevent invalid tags |
references/tooling-ruff.md | Ruff-only setup (replaces black/isort), mypy config, pre-commit, asyncio_mode=auto |
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.
1. Skill Trigger
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 projectUnderstand versioning (
setuptools_scm, PEP 440, semver, static versioning)Understand PyPA specs:
py.typed,MANIFEST.in,RECORD, classifiersPublish 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".
2. 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-libraryPython import name: underscores —
my_python_libraryCheck availability: https://pypi.org/search/ before starting
Avoid shadowing popular packages (verify
pip install <name>fails first)
3. 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 layoutQuick 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 |
4. 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.
5. 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.
6. Project Structure Templates
A. src/ Layout (Recommended default for new projects)
your-package/
├── src/
│ └── your_package/
│ ├── __init__.py # Public API: __all__, __version__
│ ├── py.typed # PEP 561 marker — EMPTY FILE
│ ├── core.py # Primary implementation
│ ├── client.py # (API client type) or remove
│ ├── cli.py # (CLI type) click/typer commands, or remove
│ ├── config.py # Settings / configuration dataclass
│ ├── exceptions.py # Custom exception hierarchy
│ ├── models.py # Data classes, Pydantic models, TypedDicts
│ ├── utils.py # Internal helpers (prefix _utils if private)
│ ├── types.py # Shared type aliases and TypeVars
│ └── backends/ # (Plugin pattern) — remove if not needed
│ ├── __init__.py # Protocol / ABC interface definition
│ ├── memory.py # Default zero-dep implementation
│ └── redis.py # Optional heavy implementation
├── tests/
│ ├── __init__.py
│ ├── conftest.py # Shared fixtures
│ ├── unit/
│ │ ├── __init__.py
│ │ ├── test_core.py
│ │ ├── test_config.py
│ │ └── test_models.py
│ ├── integration/
│ │ ├── __init__.py
│ │ └── test_backends.py
│ └── e2e/ # Optional: end-to-end tests
│ └── __init__.py
├── docs/ # Optional: mkdocs or sphinx
├── scripts/
│ └── scaffold.py
├── .github/
│ ├── workflows/
│ │ ├── ci.yml
│ │ └── publish.yml
│ └── ISSUE_TEMPLATE/
│ ├── bug_report.md
│ └── feature_request.md
├── .pre-commit-config.yaml
├── pyproject.toml
├── CHANGELOG.md
├── CONTRIBUTING.md
├── SECURITY.md
├── LICENSE
├── README.md
└── .gitignoreB. Flat Layout (Small / focused packages)
your-package/
├── your_package/ # ← at root, not inside src/
│ ├── __init__.py
│ ├── py.typed
│ └── ... (same internal structure)
├── tests/
└── ... (same top-level files)C. Namespace / Monorepo Layout (Multiple related packages)
your-org/
├── packages/
│ ├── your-org-core/
│ │ ├── src/your_org/core/
│ │ └── pyproject.toml
│ ├── your-org-http/
│ │ ├── src/your_org/http/
│ │ └── pyproject.toml
│ └── your-org-cli/
│ ├── src/your_org/cli/
│ └── pyproject.toml
├── .github/workflows/
└── README.mdEach 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).
Internal Module Guidelines
| File | Purpose | When to include |
|---|---|---|
__init__.py | Public API surface; re-exports; __version__ | Always |
py.typed | PEP 561 typed-package marker (empty) | Always |
core.py | Primary class / main logic | Always |
config.py | Settings dataclass or Pydantic model | When configurable |
exceptions.py | Exception hierarchy (YourBaseError → specifics) | Always |
models.py | Data models / DTOs / TypedDicts | When data-heavy |
utils.py | Internal helpers (not part of public API) | As needed |
types.py | Shared TypeVar, TypeAlias, Protocol definitions | When complex typing |
cli.py | CLI entry points (click/typer) | CLI type only |
backends/ | Plugin/strategy pattern | When swappable implementations |
_compat.py | Python version compatibility shims | When 3.9–3.13 compat needed |
7. Versioning Strategy
PEP 440 — The Standard
Canonical form: N[.N]+[{a|b|rc}N][.postN][.devN]
Examples:
1.0.0 Stable release
1.0.0a1 Alpha (pre-release)
1.0.0b2 Beta
1.0.0rc1 Release candidate
1.0.0.post1 Post-release (e.g., packaging fix only)
1.0.0.dev1 Development snapshot (not for PyPI)Semantic Versioning (recommended)
MAJOR.MINOR.PATCH
MAJOR: Breaking API change (remove/rename public function/class/arg)
MINOR: New feature, fully backward-compatible
PATCH: Bug fix, no API changeDynamic 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 checkoutsRequired pyproject.toml config:
[tool.setuptools_scm]
version_scheme = "post-release"
local_scheme = "no-local-version" # Prevents +g<hash> from breaking PyPI uploadsCritical: 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.
Static versioning (flit, hatchling manual, poetry)
# your_package/__init__.py
__version__ = "1.0.0" # Update this before every releaseVersion 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.*" # FragileVersion 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.
Where to Go Next
After understanding decisions and structure:
Set up
pyproject.toml→references/pyproject-toml.mdAll four backend templates (setuptools+scm, hatchling, flit, poetry), full tool configs,py.typedsetup, versioning config.Write your library code →
references/library-patterns.mdOOP/SOLID principles, type hints (PEP 484/526/544/561), core class design, factory functions,__init__.py, plugin/backend pattern, CLI entry point.Add tests and code quality →
references/testing-quality.mdconftest.py, unit/backend/async tests, parametrize, ruff/mypy/pre-commit setup.Set up CI/CD and publish →
references/ci-publishing.mdci.yml,publish.ymlwith Trusted Publishing (OIDC, no API tokens), CHANGELOG format, release checklist.Polish for community/OSS →
references/community-docs.mdREADME sections, docstring format, CONTRIBUTING, SECURITY, issue templates, anti-patterns table, and master release checklist.Design backends, config, transport, CLI →
references/architecture-patterns.mdBackend 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.mdPEP 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.mdBranch strategy, branch protection rules, OIDC Trusted Publishing setup, tag author validation in CI, tag format enforcement, full governedpublish.yml.Simplify tooling with Ruff →
references/tooling-ruff.mdRuff-only setup replacing black/isort/flake8, mypy config, pre-commit hooks, asyncio_mode=auto (remove @pytest.mark.asyncio), migration guide.
Files
- ATTRIBUTION.mdAdded by AutoGineer897 B
- LICENSELicence file added by AutoGineer1.0 KiB
- SKILL.md18.7 KiB
- references/architecture-patterns.md15.8 KiB
- references/ci-publishing.md7.9 KiB
- references/community-docs.md13.0 KiB
- references/library-patterns.md17.7 KiB
- references/pyproject-toml.md13.0 KiB
- references/release-governance.md10.4 KiB
- references/testing-quality.md6.4 KiB
- references/tooling-ruff.md9.2 KiB
- references/versioning-strategy.md10.9 KiB
- scripts/scaffold.pyScript22.0 KiB
scripts/scaffold.py
#!/usr/bin/env python3
"""
scaffold.py — Generate a production-grade Python PyPI package structure.
Usage:
python scaffold.py --name my-package
python scaffold.py --name my-package --layout src
python scaffold.py --name my-package --build hatchling
Options:
--name PyPI package name (lowercase, hyphens). Required.
--layout 'flat' (default) or 'src'.
--build 'setuptools' (default, uses setuptools_scm) or 'hatchling'.
--author Author name (default: Your Name).
--email Author email (default: [email protected]).
--output Output directory (default: current directory).
"""
import argparse
import os
import sys
import textwrap
from pathlib import Path
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def pkg_name(pypi_name: str) -> str:
"""Convert 'my-pkg' → 'my_pkg'."""
return pypi_name.replace("-", "_")
def write(path: Path, content: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(textwrap.dedent(content).lstrip(), encoding="utf-8")
print(f" created {path}")
def touch(path: Path) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.touch()
print(f" created {path}")
# ---------------------------------------------------------------------------
# File generators
# ---------------------------------------------------------------------------
def gen_pyproject_setuptools(name: str, mod: str, author: str, email: str, layout: str) -> str:
packages_find = (
'where = ["src"]' if layout == "src" else f'include = ["{mod}*"]'
)
pkg_data_key = f"src/{mod}" if layout == "src" else mod
pythonpath = "" if layout == "src" else '\npythonpath = ["."]'
return f'''\
[build-system]
requires = ["setuptools>=68", "wheel", "setuptools_scm"]
build-backend = "setuptools.build_meta"
[project]
name = "{name}"
dynamic = ["version"]
description = "<your description>"
readme = "README.md"
requires-python = ">=3.10"
license = {{text = "MIT"}}
authors = [
{{name = "{author}", email = "{email}"}},
]
keywords = [
"python",
# Add 10-15 specific keywords — they affect PyPI discoverability
]
classifiers = [
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
"Topic :: Software Development :: Libraries :: Python Modules",
"Typing :: Typed",
]
dependencies = [
# List your runtime dependencies here. Keep them minimal.
# Example: "httpx>=0.24", "pydantic>=2.0"
]
]
[project.optional-dependencies]
redis = [
"redis>=4.2",
]
dev = [
"pytest>=7.0",
"pytest-asyncio>=0.21",
"httpx>=0.24",
"pytest-cov>=4.0",
"ruff>=0.4",
"black>=24.0",
"isort>=5.13",
"mypy>=1.0",
"pre-commit>=3.0",
"build",
"twine",
]
[project.urls]
Homepage = "https://github.com/yourusername/{name}"
Documentation = "https://github.com/yourusername/{name}#readme"
Repository = "https://github.com/yourusername/{name}"
"Bug Tracker" = "https://github.com/yourusername/{name}/issues"
Changelog = "https://github.com/yourusername/{name}/blob/master/CHANGELOG.md"
[tool.setuptools.packages.find]
{packages_find}
[tool.setuptools.package-data]
{mod} = ["py.typed"]
[tool.setuptools_scm]
version_scheme = "post-release"
local_scheme = "no-local-version"
[tool.ruff]
target-version = "py310"
line-length = 100
[tool.ruff.lint]
select = ["E", "F", "W", "I", "N", "UP", "B", "SIM", "C4", "PTH"]
[tool.ruff.lint.per-file-ignores]
"tests/*" = ["S101"]
[tool.black]
line-length = 100
target-version = ["py310", "py311", "py312", "py313"]
[tool.isort]
profile = "black"
line_length = 100
[tool.mypy]
python_version = "3.10"
warn_return_any = true
warn_unused_configs = true
disallow_untyped_defs = true
ignore_missing_imports = true
strict = false
[tool.pytest.ini_options]
asyncio_mode = "auto"
testpaths = ["tests"]{pythonpath}
python_files = "test_*.py"
python_classes = "Test*"
python_functions = "test_*"
addopts = "-v --tb=short --cov={mod} --cov-report=term-missing"
[tool.coverage.run]
source = ["{mod}"]
omit = ["tests/*"]
[tool.coverage.report]
fail_under = 80
show_missing = true
'''
def gen_pyproject_hatchling(name: str, mod: str, author: str, email: str) -> str:
return f'''\
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
name = "{name}"
version = "0.1.0"
description = "<your description>"
readme = "README.md"
requires-python = ">=3.10"
license = {{text = "MIT"}}
authors = [
{{name = "{author}", email = "{email}"}},
]
keywords = ["python"]
classifiers = [
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Typing :: Typed",
]
dependencies = [
# List your runtime dependencies here.
]
[project.optional-dependencies]
dev = [
"pytest>=7.0",
"pytest-asyncio>=0.21",
"httpx>=0.24",
"pytest-cov>=4.0",
"ruff>=0.4",
"black>=24.0",
"isort>=5.13",
"mypy>=1.0",
"pre-commit>=3.0",
"build",
"twine",
]
[project.urls]
Homepage = "https://github.com/yourusername/{name}"
Changelog = "https://github.com/yourusername/{name}/blob/master/CHANGELOG.md"
[tool.hatch.build.targets.wheel]
packages = ["{mod}"]
[tool.hatch.build.targets.wheel.sources]
"{mod}" = "{mod}"
[tool.ruff]
target-version = "py310"
line-length = 100
[tool.black]
line-length = 100
[tool.isort]
profile = "black"
[tool.mypy]
python_version = "3.10"
disallow_untyped_defs = true
ignore_missing_imports = true
[tool.pytest.ini_options]
asyncio_mode = "auto"
testpaths = ["tests"]
addopts = "-v --tb=short --cov={mod} --cov-report=term-missing"
[tool.coverage.report]
fail_under = 80
show_missing = true
'''
def gen_init(name: str, mod: str) -> str:
return f'''\
"""{name}: <one-line description>."""
from importlib.metadata import PackageNotFoundError, version
try:
__version__ = version("{name}")
except PackageNotFoundError:
__version__ = "0.0.0-dev"
from {mod}.core import YourClient
from {mod}.config import YourSettings
from {mod}.exceptions import YourPackageError
__all__ = [
"YourClient",
"YourSettings",
"YourPackageError",
"__version__",
]
'''
def gen_core(mod: str) -> str:
return f'''\
from __future__ import annotations
from {mod}.exceptions import YourPackageError
class YourClient:
"""
Main entry point for <your purpose>.
Args:
api_key: Required authentication credential.
timeout: Request timeout in seconds. Defaults to 30.
retries: Number of retry attempts. Defaults to 3.
Raises:
ValueError: If api_key is empty or timeout is non-positive.
Example:
>>> from {mod} import YourClient
>>> client = YourClient(api_key="sk-...")
>>> result = client.process(data)
"""
def __init__(
self,
api_key: str,
timeout: int = 30,
retries: int = 3,
) -> None:
if not api_key:
raise ValueError("api_key must not be empty")
if timeout <= 0:
raise ValueError("timeout must be positive")
self._api_key = api_key
self.timeout = timeout
self.retries = retries
def process(self, data: dict) -> dict:
"""
Process data and return results.
Args:
data: Input dictionary to process.
Returns:
Processed result as a dictionary.
Raises:
YourPackageError: If processing fails.
"""
raise NotImplementedError
'''
def gen_exceptions(mod: str) -> str:
return f'''\
class YourPackageError(Exception):
"""Base exception for {mod}."""
class YourPackageConfigError(YourPackageError):
"""Raised on invalid configuration."""
'''
def gen_backends_init() -> str:
return '''\
from abc import ABC, abstractmethod
class BaseBackend(ABC):
"""Abstract storage backend interface."""
@abstractmethod
async def get(self, key: str) -> str | None:
"""Retrieve a value by key. Returns None if not found."""
...
@abstractmethod
async def set(self, key: str, value: str, ttl: int | None = None) -> None:
"""Store a value. Optional TTL in seconds."""
...
@abstractmethod
async def delete(self, key: str) -> None:
"""Delete a key."""
...
'''
def gen_memory_backend() -> str:
return '''\
from __future__ import annotations
import asyncio
import time
from . import BaseBackend
class MemoryBackend(BaseBackend):
"""Thread-safe in-memory backend. Zero extra dependencies."""
def __init__(self) -> None:
self._store: dict[str, tuple[str, float | None]] = {}
self._lock = asyncio.Lock()
async def get(self, key: str) -> str | None:
async with self._lock:
entry = self._store.get(key)
if entry is None:
return None
value, expires_at = entry
if expires_at is not None and time.time() > expires_at:
del self._store[key]
return None
return value
async def set(self, key: str, value: str, ttl: int | None = None) -> None:
async with self._lock:
expires_at = time.time() + ttl if ttl is not None else None
self._store[key] = (value, expires_at)
async def delete(self, key: str) -> None:
async with self._lock:
self._store.pop(key, None)
'''
def gen_conftest(name: str, mod: str) -> str:
return f'''\
import pytest
from {mod}.backends.memory import MemoryBackend
from {mod}.core import YourClient
@pytest.fixture
def memory_backend() -> MemoryBackend:
return MemoryBackend()
@pytest.fixture
def client(memory_backend: MemoryBackend) -> YourClient:
return YourClient(
api_key="test-key",
backend=memory_backend,
)
'''
def gen_test_core(mod: str) -> str:
return f'''\
import pytest
from {mod} import YourClient
from {mod}.exceptions import YourPackageError
def test_client_creates_with_valid_key() -> None:
client = YourClient(api_key="sk-test")
assert client is not None
def test_client_raises_on_empty_key() -> None:
with pytest.raises(ValueError, match="api_key"):
YourClient(api_key="")
def test_client_raises_on_invalid_timeout() -> None:
with pytest.raises(ValueError, match="timeout"):
YourClient(api_key="sk-test", timeout=-1)
'''
def gen_test_backends() -> str:
return '''\
import pytest
from your_package.backends.memory import MemoryBackend
@pytest.mark.asyncio
async def test_set_and_get() -> None:
backend = MemoryBackend()
await backend.set("key1", "value1")
result = await backend.get("key1")
assert result == "value1"
@pytest.mark.asyncio
async def test_get_missing_key_returns_none() -> None:
backend = MemoryBackend()
result = await backend.get("nonexistent")
assert result is None
@pytest.mark.asyncio
async def test_delete_removes_key() -> None:
backend = MemoryBackend()
await backend.set("key1", "value1")
await backend.delete("key1")
result = await backend.get("key1")
assert result is None
@pytest.mark.asyncio
async def test_different_keys_are_independent() -> None:
backend = MemoryBackend()
await backend.set("key1", "a")
await backend.set("key2", "b")
assert await backend.get("key1") == "a"
assert await backend.get("key2") == "b"
'''
def gen_ci_yml(name: str, mod: str) -> str:
return f'''\
name: CI
on:
push:
branches: [main, master]
pull_request:
branches: [main, master]
jobs:
lint:
name: Lint, Format & Type Check
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.11"
- name: Install dev dependencies
run: pip install -e ".[dev]"
- name: ruff
run: ruff check .
- name: black
run: black . --check
- name: isort
run: isort . --check-only
- name: mypy
run: mypy {mod}/
test:
name: Test (Python ${{{{ matrix.python-version }}}})
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.10", "3.11", "3.12", "3.13"]
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/setup-python@v5
with:
python-version: ${{{{ matrix.python-version }}}}
- name: Install dependencies
run: pip install -e ".[dev]"
- name: Run tests with coverage
run: pytest --cov --cov-report=xml
- name: Upload coverage
uses: codecov/codecov-action@v4
with:
fail_ci_if_error: false
'''
def gen_publish_yml() -> str:
return '''\
name: Publish to PyPI
on:
push:
tags:
- "v*.*.*"
jobs:
build:
name: Build distribution
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/setup-python@v5
with:
python-version: "3.11"
- name: Install build tools
run: pip install build twine
- name: Build package
run: python -m build
- name: Check distribution
run: twine check dist/*
- uses: actions/upload-artifact@v4
with:
name: dist
path: dist/
publish:
name: Publish to PyPI
needs: build
runs-on: ubuntu-latest
environment: pypi
permissions:
id-token: write
steps:
- uses: actions/download-artifact@v4
with:
name: dist
path: dist/
- name: Publish to PyPI
uses: pypa/gh-action-pypi-publish@release/v1
'''
def gen_precommit() -> str:
return '''\
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.4.4
hooks:
- id: ruff
args: [--fix]
- id: ruff-format
- repo: https://github.com/psf/black
rev: 24.4.2
hooks:
- id: black
- repo: https://github.com/pycqa/isort
rev: 5.13.2
hooks:
- id: isort
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.10.0
hooks:
- id: mypy
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.6.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
- id: check-toml
- id: check-merge-conflict
- id: debug-statements
- id: no-commit-to-branch
args: [--branch, master, --branch, main]
'''
def gen_changelog(name: str) -> str:
return f'''\
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
---
## [Unreleased]
### Added
- Initial project scaffold
[Unreleased]: https://github.com/yourusername/{name}/commits/master
'''
def gen_readme(name: str, mod: str) -> str:
return f'''\
# {name}
> One-line description — what it does and why it's useful.
[](https://pypi.org/project/{name}/)
[](https://pypi.org/project/{name}/)
[](LICENSE)
## Installation
```bash
pip install {name}
```
## Quick Start
```python
from {mod} import YourClient
client = YourClient(api_key="sk-...")
result = client.process({{"input": "value"}})
print(result)
```
## Configuration
| Parameter | Type | Default | Description |
|---|---|---|---|
| api_key | str | required | Authentication credential |
| timeout | int | 30 | Request timeout in seconds |
| retries | int | 3 | Number of retry attempts |
## Contributing
See [CONTRIBUTING.md](./CONTRIBUTING.md)
## Changelog
See [CHANGELOG.md](./CHANGELOG.md)
## License
MIT — see [LICENSE](./LICENSE)
'''
def gen_setup_py() -> str:
return '''\
# Thin shim for legacy editable install compatibility.
# All configuration lives in pyproject.toml.
from setuptools import setup
setup()
'''
def gen_license(author: str) -> str:
return f'''\
MIT License
Copyright (c) 2026 {author}
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
'''
# ---------------------------------------------------------------------------
# Main scaffold
# ---------------------------------------------------------------------------
def scaffold(
name: str,
layout: str,
build: str,
author: str,
email: str,
output: str,
) -> None:
mod = pkg_name(name)
root = Path(output) / name
pkg_root = root / "src" / mod if layout == "src" else root / mod
print(f"\nScaffolding {name!r} ({layout} layout, {build} build backend)\n")
# Package source
touch(pkg_root / "py.typed")
write(pkg_root / "__init__.py", gen_init(name, mod))
write(pkg_root / "core.py", gen_core(mod))
write(pkg_root / "exceptions.py", gen_exceptions(mod))
write(pkg_root / "backends" / "__init__.py", gen_backends_init())
write(pkg_root / "backends" / "memory.py", gen_memory_backend())
# Tests
write(root / "tests" / "__init__.py", "")
write(root / "tests" / "conftest.py", gen_conftest(name, mod))
write(root / "tests" / "test_core.py", gen_test_core(mod))
write(root / "tests" / "test_backends.py", gen_test_backends())
# CI
write(root / ".github" / "workflows" / "ci.yml", gen_ci_yml(name, mod))
write(root / ".github" / "workflows" / "publish.yml", gen_publish_yml())
write(
root / ".github" / "ISSUE_TEMPLATE" / "bug_report.md",
"""\
---
name: Bug Report
about: Report a reproducible bug
labels: bug
---
**Python version:**
**Package version:**
**Describe the bug:**
**Minimal reproducible example:**
```python
# paste here
```
**Expected behavior:**
**Actual behavior:**
""",
)
write(
root / ".github" / "ISSUE_TEMPLATE" / "feature_request.md",
"""\
---
name: Feature Request
about: Suggest a new feature
labels: enhancement
---
**Problem this would solve:**
**Proposed solution:**
**Alternatives considered:**
""",
)
# Config files
write(root / ".pre-commit-config.yaml", gen_precommit())
write(root / "CHANGELOG.md", gen_changelog(name))
write(root / "README.md", gen_readme(name, mod))
write(root / "LICENSE", gen_license(author))
# pyproject.toml + setup.py
if build == "setuptools":
write(root / "pyproject.toml", gen_pyproject_setuptools(name, mod, author, email, layout))
write(root / "setup.py", gen_setup_py())
else:
write(root / "pyproject.toml", gen_pyproject_hatchling(name, mod, author, email))
# .gitignore
write(
root / ".gitignore",
"""\
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
build/
dist/
*.egg-info/
.eggs/
*.egg
.env
.venv
venv/
.mypy_cache/
.ruff_cache/
.pytest_cache/
htmlcov/
.coverage
cov_annotate/
*.xml
""",
)
print(f"\nDone! Created {root.resolve()}")
print("\nNext steps:")
print(f" cd {name}")
print(" git init && git add .")
print(' git commit -m "chore: initial scaffold"')
print(" pip install -e '.[dev]'")
print(" pre-commit install")
print(" pytest")
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
def main() -> None:
parser = argparse.ArgumentParser(
description="Scaffold a production-grade Python PyPI package."
)
parser.add_argument(
"--name",
required=True,
help="PyPI package name (lowercase, hyphens). Example: my-package",
)
parser.add_argument(
"--layout",
choices=["flat", "src"],
default="flat",
help="Project layout: 'flat' (default) or 'src'.",
)
parser.add_argument(
"--build",
choices=["setuptools", "hatchling"],
default="setuptools",
help="Build backend: 'setuptools' (default, uses setuptools_scm) or 'hatchling'.",
)
parser.add_argument("--author", default="Your Name", help="Author name.")
parser.add_argument("--email", default="[email protected]", help="Author email.")
parser.add_argument("--output", default=".", help="Output directory (default: .).")
args = parser.parse_args()
# Validate name
import re
if not re.match(r"^[a-z][a-z0-9\-]*$", args.name):
print(
f"Error: --name must be lowercase letters, digits, and hyphens only. Got: {args.name!r}",
file=sys.stderr,
)
sys.exit(1)
target = Path(args.output) / args.name
if target.exists():
print(f"Error: {target} already exists.", file=sys.stderr)
sys.exit(1)
scaffold(
name=args.name,
layout=args.layout,
build=args.build,
author=args.author,
email=args.email,
output=args.output,
)
if __name__ == "__main__":
main()
Requirements and compatibility
Written for: GitHub Copilot
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Needs a command-line tool, Needs Python
Security
What our scanner noticed· Low risk
- Instructions that use the network
- Scripts that your agent may run
This skill includes scripts that your agent may run. Read them before you use it.
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- First committed by
Dhruvpatel004
- Publisher
- GitHub (Official)
- Distributed by
- GitHub
- Source
- github/awesome-copilot · skills/python-pypi-package-builder · commit 797337f
- Licence
- MIT License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
- Contributors
- Dhruvpatel004
AutoGineer is not affiliated with or endorsed by Dhruvpatel004 or GitHub.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download python-pypi-package-builder.zip