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-extensionsfrom 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.
| 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.
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 0Use 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.
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.
from python_extensions import specialize
@specialize(constants={"mode": "fast"}, types={"value": int})
def convert(value, mode="safe"):
...A guard miss executes the generic function.
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.
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.
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 totalStrict 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.
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.
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.
| 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 |
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 pytestFor changes to the repository:
python -m compileall -q src tests tools benchmarks/scripts
python -m pytest
python tools/check_repo.pyLong stress/differential harnesses are separate from normal pull-request feedback; see Contributing.
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 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.
- 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.
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.