Skip to content

Latest commit

 

History

13 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

cpython-extensions

CPython 3.13 extensions for fast switch dispatch, guarded specialization, bytecode inlining, and verified local goto.

Python Implementation License Typing

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 .name and label .name are source markers recognized inside @enable_goto functions; 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

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.

About

Production-oriented CPython 3.13 bytecode extensions for switch dispatch, function inlining, and validated goto.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages