/tiran-skills:port-to-python-limited-apifrom tiran-skills
Ports hand-written C/C++ CPython extensions from the version-specific C API to the Limited API (Py_LIMITED_API) for stable-ABI abi3 wheels. Covers heap types, module state, multi-phase init, API substitutions, and build flags for meson-python, scikit-build-core, maturin, and setuptools. Optionally targets Python 3.15 abi3t for free-threaded builds.
Ships in tiran-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Status: Experimental — grounded in the CPython C-API docs and the PEP 803 / 793 texts (linked below), but the packaged workflow is a new draft: review the diff and the built wheels, and test on every Python version you claim.
Convert a hand-written CPython C/C++ extension from the version-specific API (a
new cpXY wheel per release) to the Limited API, so one abi3 wheel per platform
loads on that Python and every later one. Optionally then target 3.15 abi3t for
a single wheel that also covers the free-threaded build. Work the steps in order; each
cites the reference holding its code and tables.
Scope. Extensions written directly against Python.h. Not pybind11 (not
limited-API-compatible — migrate to nanobind via
pybind11-to-nanobind) or the PyTorch C++ ABI
(port-to-torch-stable-abi). Cython/PyO3
projects take the Code-generator short path below (a build flag, not a hand port).
Why (and why not). Payoff: a smaller build/CI/PyPI matrix and forward
compatibility — an abi3 wheel built at the 3.12 floor imports on 3.12 and every
later CPython with no rebuild; abi3t extends that to free-threaded 3.15+. Cost: the
limited API is a subset (fast macros like PyList_GET_ITEM are gone, a modest
perf hit) and the port is a real refactor (heap types, module state, multi-phase
init); abi3t is a hard 3.15 boundary with no variable-size types. Full analysis and
the ABI/wheel-tag model: reference/background.md — read it first if the port isn't
yet decided.
References — open each only at the step that cites it:
background.md — API vs ABI, the three ABIs + wheel tags, benefits/drawbacks.heap-types.md (steps 3–4) — static PyTypeObject → heap type, GC rules, state.module-init.md (steps 6–7) — single- → multi-phase init → PyModExport (abi3t).api-substitutions.md (step 5) — non-limited → limited swaps; what's not in abi3.build-systems.md (step 8) — flags + abi3 / abi3.abi3t tags per backend.Deterministic tooling (offer in step 1; don't hand-edit what they automate):
pythoncapi-compat — a header
that back-fills modern C API onto old Pythons + upgrade_pythoncapi.py, which
rewrites source to use it (step 5). Lets one source compile from a low floor up;
regex-based, so review its diff.abi3audit — verifies a .so/wheel is
actually abi3-clean (step 9); nothing in pip/CPython enforces the tag.There is no automatic static→heap rewriter — step 3 is a guided manual edit.
Authoritative sources (they win over this skill):
Definition of done: builds with Py_LIMITED_API (or Py_TARGET_ABI3T) at the
chosen floor; the wheel carries the abi3 (or abi3.abi3t) tag and the .so is
*.abi3.so / *.abi3t.so; abi3audit is clean; imports and passes tests on
every claimed version — including a free-threaded build for abi3t.
Guardrails. Read
../GUARDRAILS.md: check upstream for prior work first; work in a project-local.venvwith uv; don't delete content or commit/push without approval (never tomain); match the project's C style.
Check upstream first (../GUARDRAILS.md → Prior work): a
limited-API port is a common maintainer project. Find the repo (git remote -v,
[project.urls]; if a fork, gh repo view --json parent) and search issues + PRs for
limited API, Py_LIMITED_API, abi3, abi3t, stable ABI, PyType_FromSpec,
heap type, free-threading. Report findings before porting.
Then inventory the surface:
# static types, single-phase init, blockers
grep -rnE 'static PyTypeObject|PyVarObject_HEAD_INIT|PyType_Ready|PyModule_Create|PyInit_' src/ *.c *.cpp 2>/dev/null
# non-limited macros / field access (the refactor surface)
grep -rnE 'PyList_GET_ITEM|PyList_SET_ITEM|PyTuple_GET_ITEM|->ob_type|->ob_refcnt|->ob_size|_Py[A-Z]|tp_print' src/ *.c *.cpp 2>/dev/null
# already-limited? bindings frameworks? (→ other skills)
grep -rnE 'Py_LIMITED_API|Py_TARGET_ABI3T|pybind11|nanobind|Cython|PyO3|cffi' . 2>/dev/null | head
Classify and flag blockers:
pybind11-to-nanobind) or hand-write the types.tp_itemsize ≠ 0) → cannot target abi3t on 3.15;
plain abi3 is fine._Py*, PyUnstable_*) or heavy struct access → each use
needs a supported replacement (step 5); note any with no equivalent.Offer the deterministic tooling now (above): pythoncapi-compat for step 5,
abi3audit for step 9; the static→heap edit (step 3) is manual.
Pick which stable ABI and the lowest Python it must load on — that floor is
the Py_LIMITED_API hex and the wheel's cpXY tag. The ABIs and tags:
reference/background.md. Short version:
abi3 only — one wheel across GIL-enabled CPython ≥ floor. Default floor:
3.12 (0x030C0000) — it has vectorcall and the PEP 697 APIs that make heap types
clean, and is the single-source floor if you later add abi3t. The bulk of the work.abi3 + abi3t — also cover free-threaded builds. abi3t is 3.15+ only;
its interpreters are a superset of abi3's, so ship the combined abi3.abi3t
tag (needs the step-7 PyModExport port). During the transition you typically ship
three artifacts: cpXY-abi3 (≤3.14), cp314t (free-threaded 3.14),
cp315-abi3.abi3t (3.15+) — table in reference/background.md.Lower than 3.12 (down to 3.6, even 3.2). The limited API exists since 3.2, so a
lower abi3 floor broadens coverage — use pythoncapi-compat for modern idioms that
still compile there. Obstacles as you drop: PEP 697 negative-basicsize/relative
offsets are 3.12; PyType_FromModuleAndSpec + PyType_GetModuleState are 3.9
(below that, module isolation is clumsier); typed memoryviews 3.11; vectorcall
3.12; PyModule_AddObjectRef 3.10 (back-filled). So 3.12 is the clean
recommendation; 3.6 is reachable for plain abi3; abi3t single-source is
reasonable only down to 3.12. Don't target abi3t unless free-threading is wanted
now — it's a hard pre-3.15 boundary.
If the extension is generated by Cython or PyO3 rather than hand-written against
Python.h, the generator already emits heap types, module state, and multi-phase init
for you — skip steps 3–7, do the following, then rejoin at step 8 (build) and
step 9 (verify). Full config: reference/build-systems.md.
Cython (3.1+):
limited_api: '3.12' (meson) or py_limited_api=True +
define_macros=[("Py_LIMITED_API", "0x030C0000")] (setuptools). Cython then emits
limited-API-safe C and builds heap types from specs internally, so you don't
hand-port types.cdef class can't inherit from a builtin; profiling / line tracing are unavailable;
typed memoryviews need a 3.11+ floor; some cimport cpython fast paths (e.g.
direct array.array access) don't work. Grep for these and rework them.Rust / maturin (PyO3):
pyo3 = { features = ["abi3-py312"] } (add "abi3t-py315" for
free-threaded 3.15+). PyO3 handles heap types, init, and refcounting for you.maturin build -i python3.12, then -i python3.15t) — one build emits at most one family.Both still finish at step 8 (confirm the tag and .so suffix) and step 9
(abi3audit + import/test on every claimed version, incl. free-threaded for abi3t).
The rest of the workflow (steps 3–9) is the hand-written C/C++ path.
The largest step: a static PyTypeObject uses struct internals the limited API hides,
so each type becomes a heap type built from a PyType_Spec + PyType_Slot[] and
created at runtime with PyType_FromModuleAndSpec. Walkthrough, field→slot table, and
code: reference/heap-types.md. The traps:
Py_TPFLAGS_HAVE_GC, have tp_traverse call Py_VISIT(Py_TYPE(self)), and in
tp_dealloc PyObject_GC_UnTrack first then Py_DECREF(Py_TYPE(self)) last.abi3 stays simple: the instance struct keeps PyObject_HEAD,
basicsize stays positive, member offsets absolute — PyObject goes opaque only
under abi3t (step 7). Use PyType_GetSlot for an inherited slot you can't name.static PyObject *.Heap types + the limited API push per-module state instead of C globals (also needed
for multi-phase init and subinterpreters). Define a state struct, set m_size = sizeof(state) (or Py_mod_state_size under PyModExport), reach it via
PyModule_GetState(module), and inside heap-type methods via PyType_GetModuleState
(needs PyType_FromModuleAndSpec). Patterns: reference/heap-types.md.
Run upgrade_pythoncapi.py first — it mechanically rewrites ->ob_type →
Py_TYPE, x == Py_None → Py_IsNone, and similar, and adds pythoncapi_compat.h
so the result still compiles on old Pythons. Review the diff, then hand-finish: fast
macros (PyList_GET_ITEM → PyList_GetItem), remaining field access, _Py* private
calls. Full swap table and the "no equivalent" cases: reference/api-substitutions.md.
Expect the perf trade-off — the fast macros are gone by design.
Convert single-phase PyInit_<name> (PyModule_Create) to multi-phase: a
PyModuleDef with a PyModuleDef_Slot[] (Py_mod_exec does the setup; Py_mod_gil = Py_MOD_GIL_NOT_USED under #ifdef Py_GIL_DISABLED) and a PyInit_ that just returns
PyModuleDef_Init(&def). Prerequisite for abi3t, good practice regardless.
Before/after: reference/module-init.md. Note Py_mod_gil is only the marker —
making the extension genuinely thread-safe for the free-threaded build is the
separate port-to-free-threaded-python skill.
Skip unless step 2 chose abi3t. Free-threaded 3.15 makes PyObject opaque,
breaking the static PyModuleDef. PEP 793 replaces PyInit_ with
PyModExport_<name> returning a PySlot[] (required Py_mod_abi via
PyABIInfo_VAR, plus Py_mod_name / _doc / _state_size / _methods / _slots
and the state traverse/clear/free funcs); gate it on Py_TARGET_ABI3T
(0x030f0000). Don't #define that macro yourself with a real build tool — setting
limited_api/py-api and building on a free-threaded interpreter defines it for you
(Py_LIMITED_API + Py_GIL_DISABLED ⇒ Py_TARGET_ABI3T); define it manually only as
the step-8 fallback for a tool without abi3t support. Consequences — opaque PyObject
(separate data struct + negative basicsize), no PyModuleDef (module tokens),
no variable-size types — are in reference/module-init.md. Keep the step-6 path under
#else so one source still builds abi3 for ≤3.14.
Set the define and emit the right tag / .so suffix. Per-backend recipes:
reference/build-systems.md. In brief:
py.extension_module(..., limited_api: '3.12'); for abi3.abi3t
need ≥ 0.21.0, build on free-threaded 3.15+, and bump limited_api to '3.15' there
(keyed off Py_GIL_DISABLED; no newer meson needed).wheel.py-api = "cp312" (or "cp315.cp315t" for abi3t).abi3-py312 / abi3t-py315; one build per ABI family.Extension(..., py_limited_api=True, define_macros=[("Py_LIMITED_API", "0x030C0000")]) + bdist_wheel py_limited_api="cp312".limited_api: '3.12' or the setuptools pair (Cython 3.1+).Keep requires-python / the build-tool floor in sync with the chosen hex.
The limited API covers definitions only, so verification is empirical:
uvx abi3audit dist/*.whl (or on the .so); it flags any
symbol outside the declared floor. Confirm the file is *.abi3.so / *.abi3t.so,
not *.cpython-3XY*.so. Pass the original wheel filename — abi3audit reads the
ABI tag out of the name, so a renamed wheel (foo.whl) makes it error. (nm -D +
Quansight/torch-abi-audit is a
manual fallback.)uv build, check the filename carries -abi3- (or -abi3.abi3t-),
and uvx twine check dist/*.abi3t, include a
free-threaded build. Watch for NULL-arg / struct-field pitfalls the define
misses (reference/background.md).reference/api-substitutions.md), so hunt leaks after the port with a
throwaway check. On a debug build, watch sys.gettotalrefcount() hold steady
across a loop (python -X showrefcount ..., or python -m test -R 3:3 test_m); on
a standard build, diff a gc object census or tracemalloc snapshot. See
reference/refleak-detection.md for both, a one-harness-fits-both snippet, and
sanitizers. Run it on the lowest floor and, for abi3t, a free-threaded build.AGENTS.md (opens in a new tab)README.md (opens in a new tab)reference/api-substitutions.md (opens in a new tab)reference/background.md (opens in a new tab)reference/build-systems.md (opens in a new tab)reference/heap-types.md (opens in a new tab)reference/module-init.md (opens in a new tab)reference/refleak-detection.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
cpython-extension, stable-abi, abi3, heap-types, multi-phase-init, wheel-packaging
Other plugins' skills for the same job
npx claudepluginhub tiran/agent-skills --plugin tiran-skills12 skills in this plugin
/bootstrap-python-projectScaffold a new Python project from zero: src/ layout, PEP 621 metadata, a chosen build backend (hatchling for pure Python; meson-python / scikit-build-core / maturin for compiled) with dynamic VCS versioning, py.typed, ruff, a type checker, pytest + coverage, tox or nox via uv, and hardened GitHub Actions CI (SHA-pinned, Trusted Publisher, CodeQL/Scorecard/Dependabot). Always writes a README, LICENSE, and .gitignore. Orchestrates the choose-python-build-backend, modernize-python-metadata, ship-type-information, and secure-python-release-pipeline skills. Use when asked to start a new package, scaffold/bootstrap a Python project, set up a repo from zero, turn a loose script into a proper package, or bring an existing project up to this standard (adopt the layout, metadata, tooling, or CI it lacks)./choose-python-build-backendRecommend the right PEP 517 build backend for a new or existing Python package, and give enough context to migrate. Chooses by three axes: purelib (pure Python) vs platlib (compiled C/C++/Rust/Torch), static vs dynamic/VCS metadata, and native language/build system. Covers uv-build, flit-core, hatchling (incl. compiled via scikit-build-core[hatchling] / a custom build hook), meson-python, scikit-build-core, maturin, and setuptools (legacy). Weighs compiled-project concerns: Cython, PyTorch extensions, pybind11/nanobind bindings, the stable Python ABI (abi3 / limited API), and fast parallel builds (CMake+Ninja, Meson). Use when asked "which build backend should I use", to pick a backend for a new project, or to decide whether to move an existing project off setuptools./crypto-fips-auditAudit a Python package — and any C/C++/Go/Rust code it ships — for its use of cryptography, across three use cases: inventory what crypto a package uses at all (algorithms, providers, linkage, RNG, CA stores), find insecure or weak cryptography, and assess FIPS 140-3 / NIST compliance. Flags insecure use of approved primitives (AES-ECB, RSA PKCS#1 v1.5, static IV/nonce, `random` for secrets, timing-unsafe compares, disabled TLS verification), weak RSA/EC key sizes, and — for FIPS — refused hashes (MD5, MD4, RIPEMD-160), restricted ones (SHA-1), non-approved primitives (BLAKE2/3, ChaCha20-Poly1305, 3DES, scrypt/Argon2/bcrypt, X25519/X448 key agreement, secp256k1), vendored or statically linked crypto (bundled OpenSSL/BoringSSL/AWS-LC/NSS/GnuTLS/libgcrypt/ nettle/libsodium) that escapes the system validated module, hardcoded TLS versions/ciphers that bypass crypto-policies, bundled CA trust stores, and problematic PyPI deps (bcrypt, pycryptodome, pynacl, ecdsa, rsa, m2crypto, …). Source-first, then confirmed against the built wheel/binaries. Gathers evidence; does not certify compliance./modernize-python-metadataImprove a Python package's metadata and move it into a PEP 621 [project] table in pyproject.toml — filling in what's missing along the way. Covers the readme field (dropping the open().read() hack), SPDX license expressions, trove classifiers, well-known project URLs, authors/keywords/requires-python, dependency version constraints (avoid upper caps), PEP 735 dependency groups vs extras, and the build-system table. Keeps the existing build backend (setuptools is fine). Includes a Poetry → PEP 621 migration lens (the [tool.poetry] field map and caret/tilde → floor translation; PDM too). Use when asked to clean up packaging metadata, move metadata out of setup.py/setup.cfg, migrate a Poetry (or PDM) project to [project]/PEP 621, or improve a project's PyPI page./port-to-free-threaded-pythonMake a Python package work correctly on the free-threaded (no-GIL) CPython build (PEP 703; the cp313t/cp314t "t" ABI) and declare that it does, so importing it does not silently re-enable the GIL. Covers the pure-Python thread-safety pass (mutable global/class state, caches, contextvars vs threading.local) and, for C/C++/Cython/pybind11/nanobind/Rust-PyO3 extensions, declaring support (Py_mod_gil / PyUnstable_Module_SetGIL / the per-binding flag), fixing data races with critical sections (Py_BEGIN_CRITICAL_SECTION), PyMutex, atomics and thread-local state, the borrowed-reference hazards and their strong-reference replacements (PyList_GetItemRef, PyDict_GetItemRef), building cp3Xt wheels (meson-python, scikit-build-core, maturin, setuptools, cibuildwheel), and testing under load with ThreadSanitizer and pytest-run-parallel. Use to add free-threading / no-GIL / nogil / free-threaded / PEP 703 support, ship a cp313t/cp314t wheel, or stop the GIL being re-enabled. For a single stable-ABI abi3t wheel (3.15+) pair it with port-to-python-limited-api./port-to-meson-pythonBuild a Python package (usually with a compiled C/C++/Cython/Fortran/Rust extension) with the meson-python PEP 517 backend, or port one off a bespoke setuptools setup.py. Covers the pyproject.toml backend, the meson.build (project / extension_module / install_sources), VCS/dynamic versioning computed in meson.build, editable installs, config-settings, and abi3 / limited-API wheels. Use when asked to adopt meson-python or Meson, scaffold a new meson-python project, drop setup.py, or produce standards-based wheels.