pyscriptc
Compile annotated Python to a native binary. No CPython at runtime.
A compiler that lowers a small, annotated subset of Python to a typed IR and then to LLVM. Parsing is CPython’s own ast module. mypy is a preflight: its tree is not an input. Anything the subset does not prove is a fence, not a guess.
Try it now
uv tool install pyscriptc # or: pipx install pyscriptc / pip install pyscriptc
pyscriptc compile examples/sum_squares.py --run --call sum_squares --args '[10]' -o /tmp/sum_squares
sum_squares(10) prints 285, the same value CPython prints — from a native binary.
Install it
uv tool install pyscriptc
Requirements: CPython 3.10 or later (the IR is stamped with the interpreter that lowered it) and a clang that can assemble textual LLVM IR. pipx install pyscriptc and pip install pyscriptc work the same way.
What it does
- Lowers an annotated Python subset (strict
x: Ttyping, checked by mypy) to typed IR, then LLVM IR, then a native binary via clang orzig cc. - Anything the subset does not prove stops at a named
PSxxxxfence with a hint — it never guesses at semantics. intis a Python int:i64only when the value fits, traps on overflow, refuses literals that would truncate.//is floor division.- Island calls (
subprocess.check_output,socket.gethostname,threading,logging) embed CPython on first use — and only binaries that call them link libpython. --emit ir/--emit llvmdump the intermediate forms;--runcompiles and executes;--target+--driver zigcross-compiles.
Stack
| Layer | What it is |
|---|---|
| Parser | CPython's own ast module |
| Checker | mypy preflight + the PS1xxx/PS2xxx fence tables |
| IR | typed JSON, stamped per-interpreter (gates-v1) |
| Backend | hand-emitted LLVM IR text → clang / zig cc |
| Island | optional embedded-CPython calls, CPython-linked only when used |
| Scoring | benchmarks/ layout follows scriptc |
The design is in ARCHITECTURE.md. How to compile a script is in docs/. Contributor notes are in .agents/docs/. Programs that compile today, including an invoice, an access-log gate, and a URL allow-list, are in examples/. The benchmark layout is scriptc’s benchmarks/ directory; see benchmarks/README.md.
Licensed under Apache 2.0. Copyright 2026 Joaquin Terrasa and contributors.
Subset
The IR stamp is gates-v1. Lowered:
- Annotated functions whose parameters and return use
int,float,bool,str,bytes,list,dict, or an annotated class if,while,forover alistorrange, assignment,returnint+,-,*,//, unary-, and comparisonsfloat+,-,*, and comparisons (NaNfollows Python:nan != nan)strandbytesconcatenation, indexing, ordering, andinlenonstr,bytes,list,dict, andcollections.dequeabs,min,max,sum,sorted,ord,chr,round,isinstance,getattr, andhasattr(the attribute name is a string literal)openwith a literal moder,w,rb,wb,a, orabint(float)(toward zero) andfloat(int)- Latin-1
strandbytesmethods:strip,lstrip,rstrip,upper,lower,startswith,endswith,find,replace,split,join, plusencode()anddecode()with no extra arguments listanddictliterals, indexing, and item assignment. Assignment shares the buffertry/exceptforValueError,IndexError,KeyError,OverflowError,ZeroDivisionError,RuntimeError,Exception, and a user subclass of one of those*argsof one element type, lowered as alistof that type. Asetofintorstr: construction,add, membership,len, and iteration- Annotated classes: fields,
__init__, methods, and a single base. Layout is the parent's fields, then the class's own fields. Method lookup walks the parent.@property(getter only),@staticmethod, and@classmethodon methods. A flat@dataclassgenerates__init__from annotations.enum.IntEnumandenum.Enummembers are integer constants. A subclass ofException(or another lowered exception) can be raised and caught as its own type and as the parent import/fromagainst the closed table inpyscriptc.stdlib_queue.mathis lowered (sqrt,fabs,sin,cos,tan,exp,log,log2,log10,hypot,pow,floor,ceil,trunc,isnan,isinf, andpi,e,tau,inf,nan). The codec wave is lowered too:re(escape,findall,sub,split,compile),json(loads,dumps),urllib.parse(quote,quote_plus,unquote,unquote_plus,urlencode,parse_qs,urlsplit),base64(b64encode,b64decode, and the standard and urlsafe pairs),hashlib(md5,sha1,sha256,sha384,sha512), andstruct(pack,unpackof a literal format). The rest of the queue is lowered as a closed surface:datetime,time,collections,functools,itertools,operator,contextlib,os,posixpath,pathlib,stat,fnmatch,warnings,io,string,bisect,errno, and the island modulessys,importlib,inspect,threading,logging,asyncio,subprocess,socket,ssl, andctypes. Also lowered, as closed names:importlib.resources.files/as_file,hmac.digest/new/compare_digestfor a literalsha256/sha384/sha512(andmd5/sha1), Latin-1unicodedata,tempfile.gettempdir/gettempprefix/mkdtemp,atexit.registerof a no-argument function,shutil.copyfile/rmtree,enum.Enum/enum.IntEnumas integer members, anddataclasses.dataclassas a flat__init__. Anything outside the table fences at the import (PS2002). A name added to the queue and left out of the lowered set would fence withPS2101
Fenced (no LLVM for that file):
and/oracross two types, f-string format specs, a slice step other than 1,break,continue,finally,except as, user decorators,super(), multiple inheritance,**kwargs, keyword-only and positional-only parameters, and starred calls- String literals outside Latin-1
boolarithmetic,list[bool], anddictvalues ofbool.boolis not promoted tofloat- Calls such as
str.encode("ascii"),math.gcd,functools.partial,itertools.count,operator.itemgetter,importlib.import_module, andasyncio.runthat are outside the lowered surface withexceptcontextlib.suppress(Exc),contextlib.nullcontext(),with open(...) as name, andwith importlib.resources.as_file(...) as nameitertools.repeatanditertools.chainexcept as the iterator of aforre.findallwith more than four capturing groups. A literal pattern of two to four groups returns a tuple of strings. A dynamic pattern with two or more groups raisesValueError- Float JSON, JSON null, and non-ASCII JSON text
structformat@, a format that is not a string literal, andQvalues that do not fit ini64- Keyword arguments, including
reflags andbase64validate
// is Python floor division, including negative operands. Division by zero and signed i64 overflow abort the process. They do not wrap. math.floor, math.ceil, math.trunc, and int(float) raise OverflowError when the result does not fit in i64. An uncaught exception prints its name to stderr and exits 1.
A for target that is new in the function is stored as 0, 0.0, or "" before the loop. After for i in range(0), this subset reads i as 0. CPython would raise UnboundLocalError. A target that already had a value keeps that value when the loop body never runs.
in on a list uses ==. math.nan in [math.nan] is false here. CPython's list finds that same object by identity before it compares.
typing stays in mypy. It is not a runtime lowering. Island constants (sys.platform, sys.version, sys.executable, sys.maxsize, socket.AF_INET, ssl.OPENSSL_VERSION, ssl.HAS_SNI, stat.S_IFREG, ctypes.sizeof) are baked from the interpreter that lowers the file. sys.exit is libc exit. subprocess.check_output takes a list[str] and returns bytes. os.getenv raises KeyError when the variable is unset. date plus timedelta uses the normalized day count; datetime plus timedelta uses the whole delta.
Requirements
- CPython 3.10 or later (the IR is stamped with the interpreter that lowered it)
- uv
- Clang that can assemble textual LLVM IR
Run
uv sync
uv run pyscriptc compile examples/sum_squares.py --run --call sum_squares --args '[10]' -o /tmp/sum_squares
sum_squares(10) prints 285, the same value CPython prints. --args is a Python literal parsed with ast.literal_eval, so integers are not rounded through JSON.
Other corpus programs:
uv run pyscriptc compile examples/longer.py --run --call longer --args '["bb", "a"]' -o /tmp/longer
uv run pyscriptc compile examples/floor_div.py --run --call floor_div --args '[-3, 2]' -o /tmp/floor_div
uv run pyscriptc compile examples/gates_math.py --run --call floors -o /tmp/floors
uv run pyscriptc compile examples/gates_probe.py --run --call probe -o /tmp/probe
uv run pyscriptc compile examples/fence_method.py --emit llvm -o /tmp/fence.ll
floors() prints 3. probe() prints 0. The fence exits nonzero, names encode, and does not write LLVM. examples/wave_probe.py prints 0 when the codec wave matches CPython. examples/rest_probe.py prints 0 when the rest of the queue matches CPython. examples/fence_pickle.py exits nonzero with PS2002 because pickle is outside the import table. examples/invoice.py, examples/access_log.py, examples/request_id.py, examples/release_note.py, examples/blob_digest.py, examples/url_gate.py, and examples/hostname.py are the scripts in docs/examples.md. examples/bad_annotation.py fails in mypy before lowering. examples/big_literal.py lowers to IR, then LLVM emission refuses the integer because it does not fit in i64.
re.compile returns a Pattern with a pattern field. findall, sub, and split on that object use the field. hashlib returns an opaque Hash; hexdigest and digest are the methods that lower. urlsplit returns a SplitResult of five strings (scheme, netloc, path, query, fragment). struct.unpack is a list, so [0] is the first value. json.loads takes its type from the annotation it is assigned to, or from the return annotation. parse_qs splits on & only, which is what CPython 3.14 does. A pattern that can match empty forever, such as ()*, stops with RuntimeError once the matcher spends its fuel. re.error, struct.error, and binascii.Error surface here as ValueError.
--emit ir writes the JSON IR. --emit llvm writes textual LLVM. The CPython version is a field on the module. Emitting LLVM from an IR stamped by a different version is an error: re-lower it and re-run the corpus.
Benchmarks
uv run python -m benchmarks.baseline.run --check
uv run python -m benchmarks.runtime.run --runs=5
uv run python -m benchmarks.scaling.run
benchmarks/baseline/reference.json is the reference metric set: wall time and peak RSS for each lowered workload, against the same call under CPython. Printed figures are speedups, Nx CPython, the reciprocal of the stored pyscriptc/CPython ratio, so a larger number is a bigger gain. --check still compares the stored ratios: it fails when a time ratio grows past 2× that set, or an RSS ratio grows past 1.25×. A reference of 10.0x CPython therefore fails once the run prints less than 5.0x.
The kernel geomean is the original four loops. The stdlib rows time every module that has a lowered call, including the builtin helpers. importlib.import_module and asyncio.run are fences, so those calls are not timed. importlib.resources, hmac, and Latin-1 unicodedata have their own rows. Calls that embed CPython (socket.gethostname, inspect.cleandoc, threading, logging, subprocess.check_output) are the island group: they link libpython, and their speedup sits near 1x CPython. benchmarks/adoption records why pyperformance, click, typer, pip, and black are not compiled suites yet.
Telemetry
Release builds collect anonymous usage metrics with PostHog (EU host): the subcommand you ran, pyscriptc/python versions, platform, compile duration, and the first PSxxxx fence code when a file fails to lower. Never sent: file names, paths, or source text. The machine id is a salted sha256 that is not reversible.
Telemetry is off in CI and a no-op in dev checkouts (no baked-in token). One stderr line announces it on first use. Disable it with any of:
pyscriptc telemetry disable # writes ~/.config/pyscriptc/config.toml
export PYSC_NO_TELEMETRY=1
export DO_NOT_TRACK=1
pyscriptc telemetry status shows the effective state and why.
Checks
uv run ruff check .
uv run ruff format --check .
uv run pytest
What this does not prove
A new CPython release is not supported yet in the product sense. The stamp and the fences are the hooks that make that possible later: unknown syntax fails closed, and the backend will not silently compile IR from an interpreter it has not been run against. Island calls embed that same interpreter, and only the binary that actually calls them links libpython.
Metadata
Release files for pyscriptc 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| pyscriptc-0.1.0.tar.gz | 268.6 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| pyscriptc-0.1.0-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 475.7 kB
Release files / pyscriptc-0.1.0.tar.gz
| Download URL | pyscriptc-0.1.0.tar.gz |
|---|---|
| Size | 268.6 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
012357c0652121eebf28185e1380c95769911e01d68436550388510aab5b60f1
|
|
BLAKE2b-256 checksum How to use checksums |
dd4aaf3f4540186190db5df16d470a335e15b518cabd7cf5b21706629cf082c4
|
| 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 Oct 17, 2026.
Transparency logRelease files / pyscriptc-0.1.0-py3-none-any.whl
| Download URL | pyscriptc-0.1.0-py3-none-any.whl |
|---|---|
| Size | 207.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
0a2ac88e10f74b7e94665403cebea1052ac8b8d30e3a6d6c30e95a44d0b38bca
|
|
BLAKE2b-256 checksum How to use checksums |
84240fad9fe4d338eb49e7b3b5763337df3a0041bba4c18e441790433d27ea12
|
| 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 Oct 17, 2026.
Transparency log