cpython-extensions
CPython 3.13 extensions for fast switch dispatch, guarded specialization, bytecode inlining, and verified local goto.
The PyPI distribution is cpython-extensions; code imports python_extensions. The supported interpreter range is CPython >=3.13,<3.14.
python -m pip install cpython-extensions
from python_extensions import (
case,
enable_goto,
enable_switch,
hotpath,
inline_calls,
inline_function,
optimize_extensions,
partial,
runtime_diagnostics,
specialize,
switch,
)
goto .nameandlabel .nameare source markers recognized inside@enable_gotofunctions; they are not runtime objects to import.
What it provides
| Feature | Purpose | Recommended starting point |
|---|---|---|
| Switch | Table-backed multi-way dispatch, typed keys, guards, fallthrough, optional live dispatch | @enable_switch / mode="auto" |
| Partial | Freeze selected parameters and simplify the resulting function | explicit partial(...) |
| Specialize | Guarded constant/exact-type variants with generic fallback | explicit @specialize(...) |
| Hotpath | Bounded runtime shape discovery and promotion | policy="speed" |
| Inline | Inline registered direct calls and optimize the merged bytecode | policy="speed", binding="frozen" |
| Goto | Local jumps with CFG and exception-region validation | mode="strict" |
| Diagnostics | Validate CPython/runtime assumptions and expose feature status | automatic core checks |
The project deliberately favors semantics-preserving, fail-closed transformations over benchmark-specific shortcuts.
Quick start
Switch
from python_extensions import case, enable_switch, switch
@enable_switch
def classify(command: str) -> int:
with switch(command):
if case("read", "peek"):
return 1
if case("write"):
return 2
if case():
return 0
Use exact runtime type as part of case identity when ordinary Python mapping equality is not appropriate:
@enable_switch(case_key_mode="typed")
def exact(value):
with switch(value):
if case(1):
return "int"
if case(1.0):
return "float"
if case(True):
return "bool"
if case():
return "other"
mode="auto" uses portable lowering by default. Supplying live_threshold= is an explicit opt-in to live planning; compact portable direct/template plans can still veto live mutation. Use live modes only after benchmarking the real workload and accepting their CPython-specific concurrency/re-entry contract. See Live switch.
Partial evaluation
from python_extensions import partial
fast_parse = partial(parse, mode="fast")
Bound parameters are removed from the effective call signature and exposed to conservative constant/dead-branch simplification.
Guarded specialization
from python_extensions import specialize
@specialize(constants={"mode": "fast"}, types={"value": int})
def convert(value, mode="safe"):
...
A guard miss executes the generic function.
Adaptive hot paths
from python_extensions import hotpath
@hotpath(threshold=64, max_variants=1, policy="speed")
def decode(value, mode):
...
Profiling is bounded by shape and call budgets. Eligible monomorphic ordinary functions can warm up through sys.monitoring and promote to a verified in-frame dispatcher.
Function inlining
from python_extensions import inline_calls, inline_function
@inline_function(register_only=True)
def affine(x: int, scale: int = 4) -> int:
return x * scale + 3
@inline_calls(policy="speed")
def hot_path(x: int) -> int:
return affine(x)
binding="frozen" is a decoration-time snapshot and gives the optimizer the most freedom. Use binding="guarded" when a target may be rebound, patched, or reconfigured after decoration.
Validated goto
from python_extensions import enable_goto
@enable_goto
def countdown(n: int) -> int:
total = 0
label .loop
if n <= 0:
goto .done
total += n
n -= 1
goto .loop
label .done
return total
Strict mode rejects jumps that violate stack or exception-region invariants. Prefer ordinary structured control flow when it is already clear; goto is most useful for generated parsers/state machines and other explicitly low-level control flow.
Compose transformations
Use the canonical order rather than stacking decorators manually:
switch -> partial -> inline -> goto -> specialize/hotpath
from python_extensions import optimize_extensions
@optimize_extensions(
switch=True,
partial={"mode": "fast"},
inline={"policy": "speed"},
goto=True,
specialize={"types": {"value": int}},
)
def execute(value, mode="safe"):
...
specialize and hotpath are alternative final layers.
Runtime qualification
import python_extensions runs bounded package-owned checks for the CPython 3.13 wordcode/exception-table contract, required opcodes, CodeType.replace, the shared verifier, portable switch execution, and goto prerequisites. The import probe does not call application functions.
from python_extensions import runtime_diagnostics
print(runtime_diagnostics())
print(runtime_diagnostics(full=True))
runtime_diagnostics(full=True) additionally probes live-switch layout/native support and the lazy bytecode-dependent inline/specialization subsystems. Results are cached per process and returned as detached snapshots. See Runtime diagnostics.
Choosing modes
| Area | Default | Change it when... |
|---|---|---|
| Switch backend | mode="auto" |
A measured workload justifies an explicit portable/live choice |
| Live engine | live_engine="auto" |
Certification requires native, or diagnostics require ctypes |
| Case identity | case_key_mode="python" |
Exact runtime types must remain distinct |
| Specialization | explicit constants/types | You know the valuable stable shape |
| Hotpath | bounded adaptive defaults | Runtime discovery is preferable to manual variants |
| Inline binding | binding="frozen" |
Use guarded for replaceable targets |
| Inline policy | policy="speed" |
Use always only after measuring the tradeoff |
| Goto | mode="strict" |
unsafe is reserved for controlled experiments |
Installation notes
The optional python_extensions._livegate C extension accelerates explicit live switch modes. Portable switch and goto do not require it at runtime. Live switch is not certified for free-threaded CPython 3.13 and the native accelerator is not imported there.
Development checkout:
git clone https://github.com/Karvp/cpython-extensions.git
cd cpython-extensions
python -m venv .venv
python -m pip install -e ".[dev]"
python -m pytest
Validation
For changes to the repository:
python -m compileall -q src tests tools benchmarks/scripts
python -m pytest
python tools/check_repo.py
Long stress/differential harnesses are separate from normal pull-request feedback; see Contributing.
Release status
Version 1.3.3 is the current documented release. It is a documentation-only refinement over the published 1.3.2 corrective release; runtime implementation and retained V130 benchmark/certification evidence remain unchanged from 1.3.0.
Current source licensing is GPL-3.0-only. Earlier releases retain the licenses under which they were distributed.
Performance
Performance claims are read in this order: Normal Python vs extension support, then extension mode/backend comparisons, then release-to-release implementation overhead.
The primary V130 benchmark uses a 1,024-way source-level router and validates equivalent results before timing. On the recorded CPython 3.13.5 host, integer routing measured about 133.7× faster than the equivalent linear if/elif router and 142.7× faster than match; the extension remained in the same performance class as a hand-written dict.get control. This is a scaling claim over linear source dispatch, not a claim to beat Python dictionaries by two orders of magnitude.
The same evidence records about 1.33× for the selected frozen-inline workload and 2.67× for strict goto versus an explicit three-state dispatcher. The live-switch matrix shows that native live can substantially outperform portable mode for repeated heterogeneous in-frame VM/parser dispatch, while ordinary HTTP/direct/template routing can favor portable. The 1.3 optimization evidence records 1.94× faster monomorphic hotpath profiling along with smaller construction-time improvements in several decorators.
Canonical evidence and reproduction commands live in benchmarks/README.md, especially BENCHMARK_PRIMARY_V130. Treat all recorded timings as host-specific evidence, not guarantees for another machine or workload.
Documentation
- Comprehensive guide — usage, API choices, composition, troubleshooting.
- Architecture — transformation pipeline and invariants.
- Compatibility — supported interpreter/build boundary.
- Specialization —
partial,specialize, andhotpath. - Live switch — live execution model, safety, and workload fit.
- Runtime diagnostics — qualification lifecycle and diagnostics.
- Benchmarks — methodology and retained evidence.
- Releasing — release and publishing procedure.
- Release notes and changelog.
- Contributing and security policy.
License
The current source and 1.3.x release line are licensed under the GNU General Public License v3.0 only (GPL-3.0-only). See LICENSE.
Metadata
Release files for cpython-extensions 1.3.3
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| cpython_extensions-1.3.3.tar.gz | 492.8 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| cpython_extensions-1.3.3-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl | CPython 3.13 | CPython 3.13 | Linux glibc 2.28+ x86-64, Linux glibc 2.17+ x86-64 | Details |
Total release size: 680.0 kB
Release files / cpython_extensions-1.3.3.tar.gz
| Download URL | cpython_extensions-1.3.3.tar.gz |
|---|---|
| Size | 492.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
f0ccfadad5aa6472f914f3bac3cad15bde7de10e3769d339609c86f4146abb18
|
|
BLAKE2b-256 checksum How to use checksums |
d89a0ff85442acb26ec26da73b71fe93a3d529b5c4c8e0d90a0d08ad2f4d3610
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Aug 25, 2026.
Transparency logRelease files / cpython_extensions-1.3.3-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl
| Download URL | cpython_extensions-1.3.3-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl |
|---|---|
| Size | 187.1 kB |
| Tags | CPython 3.13 Linux glibc 2.17+ x86-64 Linux glibc 2.28+ x86-64 |
|
SHA-256 checksum How to use checksums |
d1db937be10c0977b78dae0fe925b3cf4ab31d76a928f650e754a5ff2da70306
|
|
BLAKE2b-256 checksum How to use checksums |
7a4cfbefe4b17a80f17495f084e494332586badb76b27676f75203cfa5645ead
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Aug 25, 2026.
Transparency log