Metadata-Version: 2.4
Name: cpython-extensions
Version: 1.3.3
Summary: CPython 3.13 switch/live dispatch, specialization, function inlining, and validated goto extensions
Author: Mch Stephen
License-Expression: GPL-3.0-only
Project-URL: Homepage, https://github.com/Karvp/cpython-extensions
Project-URL: Repository, https://github.com/Karvp/cpython-extensions
Project-URL: Issues, https://github.com/Karvp/cpython-extensions/issues
Project-URL: Documentation, https://github.com/Karvp/cpython-extensions/blob/main/docs/COMPREHENSIVE_GUIDE.md
Classifier: Development Status :: 5 - Production/Stable
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Intended Audience :: Developers
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: POSIX
Classifier: Operating System :: MacOS
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: <3.14,>=3.13
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: bytecode<0.18,>=0.17
Provides-Extra: test
Requires-Dist: pytest<10,>=8; extra == "test"
Requires-Dist: coverage[toml]<8,>=7.6; extra == "test"
Provides-Extra: build
Requires-Dist: build<2,>=1.2; extra == "build"
Requires-Dist: twine<7,>=5; extra == "build"
Requires-Dist: trove-classifiers>=2026.6.1.19; extra == "build"
Provides-Extra: dev
Requires-Dist: pytest<10,>=8; extra == "dev"
Requires-Dist: coverage[toml]<8,>=7.6; extra == "dev"
Requires-Dist: build<2,>=1.2; extra == "dev"
Requires-Dist: twine<7,>=5; extra == "dev"
Requires-Dist: trove-classifiers>=2026.6.1.19; extra == "dev"
Dynamic: license-file

# cpython-extensions

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

[![Python](https://img.shields.io/badge/Python-3.13-3776AB?logo=python&logoColor=white)](https://www.python.org/)
[![Implementation](https://img.shields.io/badge/implementation-CPython-306998)](https://www.python.org/)
[![License](https://img.shields.io/badge/license-GPL--3.0--only-blue)](LICENSE)
[![Typing](https://img.shields.io/badge/typing-py.typed-informational)](src/python_extensions/py.typed)

The PyPI distribution is **`cpython-extensions`**; code imports **`python_extensions`**. The supported interpreter range is **CPython `>=3.13,<3.14`**.

```bash
python -m pip install cpython-extensions
```

```python
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

```python
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:

```python
@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](docs/LIVE_SWITCH.md).

### Partial evaluation

```python
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

```python
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

```python
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

```python
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

```python
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:

```text
switch -> partial -> inline -> goto -> specialize/hotpath
```

```python
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.

```python
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](docs/RUNTIME_DIAGNOSTICS.md).

## 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:

```bash
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:

```bash
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](CONTRIBUTING.md).

## 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](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](docs/COMPREHENSIVE_GUIDE.md) — usage, API choices, composition, troubleshooting.
- [Architecture](docs/ARCHITECTURE.md) — transformation pipeline and invariants.
- [Compatibility](docs/COMPATIBILITY.md) — supported interpreter/build boundary.
- [Specialization](docs/SPECIALIZATION.md) — `partial`, `specialize`, and `hotpath`.
- [Live switch](docs/LIVE_SWITCH.md) — live execution model, safety, and workload fit.
- [Runtime diagnostics](docs/RUNTIME_DIAGNOSTICS.md) — qualification lifecycle and diagnostics.
- [Benchmarks](benchmarks/README.md) — methodology and retained evidence.
- [Releasing](docs/RELEASING.md) — release and publishing procedure.
- [Release notes](docs/RELEASE_NOTES.md) and [changelog](CHANGELOG.md).
- [Contributing](CONTRIBUTING.md) and [security policy](SECURITY.md).

## 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](LICENSE).
