Skip to main content

cpython-extensions

Production-oriented CPython 3.13 language-extension utilities for fast switch dispatch, bytecode-level function inlining, and validated local goto.

Python Implementation License Typing

The distribution is named cpython-extensions; the import package is python_extensions. The project deliberately targets CPython internals and currently supports CPython 3.13.x (>=3.13,<3.14).

python -m pip install cpython-extensions
from python_extensions import (
    case,
    enable_goto,
    enable_switch,
    inline_calls,
    inline_function,
    switch,
)

goto .name and label .name are compile-time pseudo-statements recognized inside @enable_goto functions; they are not runtime objects that need to be imported.

At a glance

Capability What it provides Production-oriented default
Switch Hash-table-style multi-way dispatch, typed key identity, guarded cases, and fallthrough mode="auto"
Inline Bytecode-level call inlining, profitability checks, shared regions, data-flow optimization policy="speed", binding="frozen"
Goto Explicit local jumps with exception-region and CFG validation mode="strict"
Verification Post-transform bytecode/control-flow verification and reports Keep enabled

The package favors general Python semantics, explicit opt-ins, and fail-closed transformation over benchmark-specific shortcuts.

Why cpython-extensions?

Python intentionally keeps its language small and structured, but some performance-sensitive or generated-code workloads benefit from lower-level control. cpython-extensions explores three bounded extensions while keeping the transformation pipeline observable and verifiable:

  • Switch — efficient multi-route dispatch without manually maintaining a dictionary of lambdas or a long if/elif ladder.
  • Inline — clone selected function bodies into callers, with profitability analysis and guarded binding when targets may change.
  • Goto — local control-flow jumps for state machines, generated parsers, and carefully audited low-level code.

This is not a replacement Python implementation and does not claim portability to PyPy or other interpreters. It is intentionally CPython-specific.

Quick start

Switch dispatch

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 Python's ordinary equality aliases are undesirable:

@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"

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)

The default binding="frozen" is the highest-optimization mode and assumes the target remains intentionally stable after transformation. Use guarded binding when a callee may be rebound or mutated:

@inline_calls(policy="always", binding="guarded")
def plugin_sensitive(x):
    return affine(x)

Guarded mode validates the callable state used by the cloned body and falls back to the ordinary call if that state no longer matches.

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 is the production default and rejects jumps that cross unsafe control-flow or exception-region boundaries.

The goto extension was inspired in part by Entian's goto, which demonstrated source-level goto/label syntax for Python. cpython-extensions implements its own CPython 3.13 transformation pipeline with strict CFG/exception-region validation and post-transform bytecode verification.

Compose extensions

from python_extensions import optimize_extensions

@optimize_extensions(
    switch=True,
    inline={"policy": "speed"},
    goto=True,
)
def execute(...):
    ...

Inspect rather than blindly trust transformed functions:

from python_extensions import explain_extensions, verify_code

print(explain_extensions(execute))
verify_code(execute.__code__)

Choosing the right modes

Area Recommended default Choose another mode when...
Switch mode="auto" You have explicitly accepted the contract of a live/self-modifying backend
Case identity case_key_mode="python" Exact runtime types such as 1, 1.0, and True must remain distinct
Inline binding binding="frozen" Use guarded for hot reload, plugins, monkey-patching, replaceable methods, or mutable defaults
Inline policy policy="speed" Use always for controlled experiments or code-size/latency tradeoffs you have measured
Goto mode="strict" unsafe is reserved for carefully audited low-level experiments
Verification enabled Do not bypass verifier failures in production

Installation

PyPI

python -m pip install cpython-extensions

Development checkout

git clone <your-repository-url>
cd cpython-extensions
python -m venv .venv

Windows PowerShell:

.venv\Scripts\Activate.ps1
python -m pip install -U pip
python -m pip install -e ".[dev]"
python -m pytest

POSIX shells:

source .venv/bin/activate
python -m pip install -U pip
python -m pip install -e ".[dev]"
python -m pytest

Verification and development gates

python -m compileall -q src tests
python -m pytest
python -m coverage run --branch -m pytest
python -m coverage report
python tools/check_repo.py

Long-running stress tests are intentionally separated from ordinary pull-request feedback. See .github/workflows/stress.yml.

Release quality

Version 1.0.4 is the current public release; 1.0.3 was the initial public release. It has been exercised on CPython 3.13.5 with package regressions, allocator/dev-mode checks, bytecode verification, multi-million-operation stress harnesses, reproducible wheel/sdist builds, and artifact-level installation tests.

See:

The project does not currently claim independent certification for free-threaded CPython (3.13t).

Benchmarks

Plain CPython vs cpython-extensions

The 1.0.4 README benchmark compares idiomatic CPython implementations with equivalent extension-backed paths. The recorded run used CPython 3.13.5 on Linux x86-64, timeit.repeat, 9 repeats, 20,000 timed batches per repeat, and 500 warm-up batches. Lower time is better.

Scenario Plain CPython With extension Relative result
8-way string routing (if/elif vs switch) 18.003 µs/batch 15.709 µs/batch 1.146× faster
Small affine helper (normal call vs inline) 19.105 µs/batch 13.967 µs/batch 1.368× faster
Countdown state loop (while vs strict goto) 13.192 µs/batch 13.288 µs/batch 0.993× (about 0.7% slower)

These are microbenchmarks, not universal performance claims. They intentionally report both wins and losses: switch and inlining benefit these particular workloads, while strict goto is primarily a control-flow expressiveness feature and is approximately performance-neutral/slightly slower here. Results vary with CPU, OS, CPython patch release, specialization state, and workload shape.

Reproduce the comparison from the repository root:

python benchmarks/scripts/benchmark_readme_baseline_v104.py \
  --json benchmarks/results/BENCHMARK_README_BASELINE_V104.json

The raw committed evidence is benchmarks/results/BENCHMARK_README_BASELINE_V104.json.

Historical benchmark drivers and recorded result artifacts remain separated from the repository root:

  • benchmarks/scripts/ — executable benchmark drivers and workers
  • benchmarks/results/ — committed benchmark JSON/text evidence

See benchmarks/README.md for layout, reproduction notes, and result-handling guidance.

Documentation

  • Comprehensive guide — complete API, performance choices, guarded/frozen semantics, composition, troubleshooting, and deployment guidance.
  • Architecture — transformation pipeline, invariants, and subsystem responsibilities.
  • Compatibility — interpreter/runtime support boundary and unsupported environments.
  • Release process — reproducible build, artifact verification, and tag/release workflow.
  • Release notes — public release summary, including 1.0.4.
  • Changelog — public release changes.
  • Contributing — development expectations and test requirements.
  • Security policy — how to report verifier, crash, or unsafe-boundary issues.

Repository metadata

Recommended GitHub settings are tracked in .github/REPOSITORY_METADATA.md. The canonical repository name is cpython-extensions and the recommended GitHub description is:

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

Contributing

Contributions are welcome when they preserve general Python semantics and avoid benchmark- or fixture-specific shortcuts. Please run the normal development gates before opening a pull request and include focused regression coverage for observable behavior changes.

See CONTRIBUTING.md.

Security

Low-level bytecode transformation can amplify interpreter/runtime assumptions. Crashes, verifier bypasses, incorrect exception-region handling, or unsafe boundary crossings should be treated as security-relevant until triaged.

See SECURITY.md.

License

This project is licensed under the Mozilla Public License 2.0 (MPL-2.0). See LICENSE.

MPL-2.0 is a file-level copyleft license: modifications to MPL-covered source files remain under MPL-2.0 when distributed, while the license permits those files to be combined with a larger work under different terms, subject to the license conditions.

Metadata

Release files for cpython-extensions 1.0.4

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for cpython-extensions 1.0.4
File Size Uploaded
cpython_extensions-1.0.4.tar.gz 325.2 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for cpython-extensions 1.0.4
File Interpreter ABI Platform
cpython_extensions-1.0.4-py3-none-any.whl Python 3 none any Details

Total release size: 459.1 kB

Release files / cpython_extensions-1.0.4.tar.gz

Download URL cpython_extensions-1.0.4.tar.gz
Size 325.2 kB
Tags Source
SHA-256 checksum
How to use checksums
2b12ebdb04e1c02dc228f7633a88b3122da92944e412509e57cb85d09d056125
BLAKE2b-256 checksum
How to use checksums
d930324e5d7ee2644aaf0521e0e1cf28218e15fa51a42828f909fac1e97f8e42
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 21, 2026.

Transparency log

Release files / cpython_extensions-1.0.4-py3-none-any.whl

Download URL cpython_extensions-1.0.4-py3-none-any.whl
Size 133.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
78cdd7c8bc993d102168890a868143a92746f19a49d82f9b37dc46b0c5184ea7
BLAKE2b-256 checksum
How to use checksums
117bcb15bc3fc8556f5d37b90b6841cd8af9c312d8a1533962f608ac651d2998
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 21, 2026.

Transparency log

Release history Release notifications | RSS feed

1.3.3

2 release files

1.3.2

2 release files

1.3.0

2 release files

1.2.0

2 release files

1.1.0

2 release files

This release

1.0.4 This release

2 release files

1.0.3

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page