Rcuddle - Run Python Native
I got tired, I really got tired of how slow Python is. Someone might say, "Just use something else or write extensions." Man, if I have to convert every script I have to native code or write C extensions like Cython, it will kill me.
I know alternatives exist, like PyPy or Codon. But PyPy is a JIT and everyone hates JITs despite how good they are (including me), and Codon is a closed ecosystem. It cannot work with most Python tools, and it even had to build its own NumPy.
I decided to take matters into my own hands, and five months ago I started a side project called rcuddle. A Python compiler, at least on the surface. When someone reads this, they will probably say, "We already have Nuitka. What's new here?"
rcuddle is an experimental Python compiler built around a simple idea: functions like this can be compiled straight to native code without going through the Python interface at every step. Take this Python code for example:
def stats(n):
total = 0
biggest = 0
smallest = n * n
for i in range(n):
v = abs((i * 7919) % 1000 - 500)
total += v
biggest = max(biggest, v)
smallest = min(smallest, v)
return smallest, biggest, total / n, int(total / n), float(total)This simple function is expensive in CPython, yet it has nothing to do with the Python VM. Normally, to optimize it you would rewrite it in Cython or slap @numba.njit on it.
In rcuddle, we don't blindly assume n is a number, because in Python someone could pass anything to stats(n). Instead, the compiler runs whole-program type inference with call-site specialization. When it sees stats called with an integer, it specializes a native version for integer inputs, and since builtins like abs, max, min, float, and int are known ahead of time, everything inside the loop stays unboxed (64-bit ints with overflow checks that fall back to arbitrary-precision ints if needed, 64-bit floats, and a flat tuple struct for the return value). At the Python boundary, a small wrapper checks the argument types: if they match, it runs the native path; if not, it falls back to standard boxed execution.
I think you got the idea. That's a simple example. Let's look at something more complex:
@dataclass
class V2:
x: float
y: floatWho doesn't use dataclasses! I know Pydantic exists, but I'm still in love with dataclasses because they give me structured data without relying on a heavy design like Pydantic or raw dicts. Dataclasses are the perfect fit for compiling to structs: their fields are typed and their initialization is strict and known.
Depending on how a class is used, rcuddle puts it into one of four tiers: if instances stay local or inside lists without escaping into dynamic Python, it becomes a Value class (an inline struct with zero heap allocations). If it escapes or gets returned, it becomes a Ref unboxed struct on rcuddle's native GC heap. If it crosses into dynamic Python code, it becomes a real Python object with native unboxed fields stored right inside it. Otherwise it stays a normal boxed Python object.
All the boilerplate methods that @dataclass normally generates at runtime (__init__, __repr__, __eq__, ordering, hashing, and so on) are expanded in the AST at compile time instead. So the dataclasses module never even loads at runtime, helpers like fields, asdict, astuple, and replace run natively, and frozen dataclasses still stay unboxed.
I won't lie. Most of those pieces are straightforward on their own: PyPy handles compatibility well, and Codon compiles dataclasses too. PyPy implements the CPython C API inside a JIT, while Codon stays isolated so it doesn't depend on CPython much.
I had to go in a new direction. I wanted to merge both: ahead-of-time native speed AND CPython compatibility. It seemed like an impossible task. It still feels like an impossible task TBH. I decided to target Python 3.12 first because so far it's the most widely used version around me (and judging by Reddit, lots of people are on it too). Under the hood, rcuddle tracks feature gates across Python 3.7 to 3.14 and never bundles CPython's standard library; it finds or downloads it for your version and pre-compiles the modules your code uses into IR at build time (which cut import asyncio startup from ~2.6 s down to ~0.4 s).
Trying to do both native speed and CPython compatibility feels like a terrible idea on the surface, especially when you think about it. Why didn't I just embed CPython to assist me on the parts I can't compile natively, like Nuitka does?
That sounds reasonable if you ask me! I didn't want to embed CPython for two reasons:
- If I build on top of CPython, everything is trapped inside CPython's runtime, so I don't get the freedom I want over memory layouts, calling conventions, or unboxed loops.
- If I fall back to embedded CPython whenever static typing fails, I end up marshaling values across the boundary or calling into
libpythonfor every dynamic operation like Nuitka does, which isn't a fast option.
So I decided to build the entire runtime from scratch in Rust. How does that help? It helps a lot indeed. The biggest problem for any project trying to run Python fast is C extensions, because compiled extensions expect the exact CPython C struct layout. Rcuddle generates matching CPython struct layouts and exports the CPython C API, so existing binary extensions and libraries like NumPy already load and work without modifying them (and NumPy array indexing even gets unboxed fast paths). For memory, native unboxed objects use rcuddle's own garbage collector (with stack scanning and compiler-generated pointer maps) plus compile-time ownership tracking for strings and objects, while boxed Python objects use reference counting and a cycle collector (currently behind an opt-in flag while the last leaks and overhead are being cleaned up).
Rcuddle solves the speed vs compatibility trade-off by splitting execution into two worlds:
- World A: Everything here is unboxed: raw ints, floats, bools, flat tuples, Value structs on the stack, or native objects and lists on the GC heap.
- World B: Everything here is boxed with a real CPython object layout, for two reasons:
- Code the typed compiler doesn't support yet falls back here (like dynamic module/class setup, async generators,
*args/**kwargs, and mixed union types). Module-level loops used to stay boxed too, but now rcuddle automatically lifts them into hidden local functions so they run unboxed in World A. - Anything crossing into C extensions has to match CPython's structs, and since World B objects already use those structs, no data copying is needed at the boundary.
- Code the typed compiler doesn't support yet falls back here (like dynamic module/class setup, async generators,
I also got plain async def coroutines and core asyncio (sleep, create_task, gather, run) compiling to unboxed state machines on a native Rust event loop, plus local generators and lambdas. In the asyncio benchmark it runs 2.6x to 3.0x faster than CPython 3.13 using 3.85x less memory. On pure numeric and class loops rcuddle beats PyPy 2x to 4x, though heavy dynamic, dict, and string code in World B is still slower than PyPy and CPython for now.
How the tokenizer works
Before any compilation happens, Python source has to be turned into tokens. Rcuddle has its own zero-dependency tokenizer ported from CPython 3.12's rules. It works directly on raw UTF-8 slices without cloning the source text, while also providing a line-streaming mode for runtime tools like Python's tokenize module.
To keep scanning fast, it uses 256-entry lookup tables for quick ASCII byte classification (digits, spaces, string prefixes, identifiers), 8-byte bit-parallel scanning to fly through comments and string bodies 8 bytes at a time, and compact Unicode tables for non-ASCII identifiers. It handles Python's layout quirks too: tracking indentation levels for indent/dedent tokens, enforcing the 200-bracket nesting limit, joining lines inside brackets, parsing type comments, and keeping a small mode stack for Python 3.12's nested f-strings alongside a legacy pre-3.12 f-string mode and version checks.
From Python code to IR
Both ahead-of-time compilation and runtime eval()/exec() share the exact same frontend pipeline:
Python source
-> Tokenizer (zero-copy scanning, indents, nested f-strings)
-> PEG Parser (generated from CPython 3.12 grammar, memoized, left recursion)
-> AST (CPython 3.12 shape, plus compile-time rewrites like @dataclass)
-> Symtable (locals, globals, closures, inlined comprehensions)
-> HIR (Python-aware control flow graph)From HIR, the pipeline splits into two paths:
- Ahead-of-time native compile: Module-level loops are lifted into local functions, then type inference, class-tier classification, and escape analysis decide what can live in World A. Typed functions and World B fallbacks are lowered to LLVM IR, compiled per function in parallel (and cached on disk), and linked with the runtime into a standalone native executable.
- Runtime VM: Dynamic calls like
eval(),exec(),compile(), and pre-lowered standard library modules run on a VM that executes the exact same HIR over World B objects, so compiled and interpreted code behave identically.
What is HIR?
HIR (High-level Intermediate Representation) is the middle ground between Python's syntax tree and LLVM IR. The AST is still nested statements with no control-flow edges, while LLVM IR is too low-level and knows nothing about Python scopes, closures, generators, or exceptions.
In HIR, every module, function, class body, or lambda becomes a register-based Control Flow Graph made of basic blocks, where each block has an explicit exception-handler edge. Instead of a stack machine like CPython bytecode, HIR uses virtual registers (temps). It isn't strict SSA because temps can merge across branches, but it enforces strict ownership rules: each temp holds either one strong reference or nothing, operations consume their inputs, and if anything raises an exception, all live temps in that block are automatically released before jumping to the handler. Things that must survive across a try or loop (like iterators or context managers) are kept in hidden local slots.
Its instructions stay at Python's level: variable and closure lookups, building functions and classes, with blocks, pattern matching, exception groups, generators, yield from, and await. HIR also has a readable text format that round-trips cleanly, which is how rcuddle caches pre-lowered standard library modules and runs them in the VM without re-parsing Python source at startup.
Benchmarks: CPython vs PyPy vs Nuitka vs rcuddle
To see where things stand today, here is a 5-run (best time) comparison against CPython 3.12, PyPy, and Nuitka on Windows (release builds, matching stdout across all four). Where memory matters, peak RSS is shown as time (s) / peak MB. For the ratio columns, numbers above 1x mean rcuddle is faster (for example, 80x = 80x faster; 0.24x = about 4.2x slower).
| Program | What it tests (snapshot) | CPython | PyPy | Nuitka | rcuddle | rcuddle vs Nuitka | rcuddle vs PyPy |
|---|---|---|---|---|---|---|---|
old_b4_particles | Module-level 1,000-particle x 4,000-step 2D sim allocating Vec objects every step | 2.132 | 0.087 | 2.216 | 0.028 | 80x | 3.1x |
typed_demo | Same 1,000-particle x 4,000-step Vec/Particle simulation inside a function | 2.224 | 0.090 | 2.307 | 0.031 | 75x | 2.9x |
typed_sim | 500 particles x 2,000 steps using @dataclass V2 vectors and Particle | 0.805 | 0.117 | 0.941 | 0.028 | 34x | 4.2x |
old_b5_sieve | Module-level 8M Sieve of Eratosthenes + 1M list comprehension | 1.936 / 116 | 0.243 / 165 | 1.039 / 122 | 0.062 / 35 | 17x | 3.9x |
typed_numeric | Collatz search up to 300,000 + 200x150 Mandelbrot set | 2.993 | 0.118 | 1.484 | 0.119 | 12.5x | 1.0x (tied) |
typed_lists | 2M list sieve + 120x120 matrix multiply + 1,500-element bubble sort | 0.507 | 0.093 | 0.458 | 0.039 | 12x | 2.4x |
old_b1_primes | Module-level trial-division prime count and sum up to 1,000,000 | 2.519 | 0.143 | 1.163 | 0.100 | 12x | 1.4x |
article | The stats(1_000_000) function shown at the top of this post | 0.296 | 0.039 | 0.247 | 0.025 | 10x | 1.6x |
typed_sim_flat | Hand-flattened typed_sim (raw float fields on Particle, inlined bounce) | 0.177 | 0.050 | 0.172 | 0.018 | 10x | 2.8x |
typed_class_local | Loop creating 300,000 Vec(i, i + 1) instances and calling v.dot(v) | 0.116 | 0.047 | 0.127 | 0.017 | 7x | 2.8x |
old_b2_fib | Module-level call to naive recursive fib(35) | 1.309 | 0.113 | 0.880 | 0.139 | 6x | 0.81x |
typed_fib | Naive recursive fib(30) | 0.139 | 0.058 | 0.113 | 0.026 | 4x | 2.3x |
showcase | Multi-module app: packages, plugins, frozen stdlib, dataclasses, asyncio, match, except*, sim/fib | 1.214 / 25 | 0.328 / 52 | 1.295 / 32 | 0.468 / 118 | 2.8x | 0.70x |
old_b3_float_mandel | Module-level 600x600 Mandelbrot + 6M-step pi integral | 1.922 | 0.115 | 1.707 | 1.482 | 1.15x (noise) | 0.08x |
typed_strings | 300,000 f-strings joined by comma + 300,000 "w" + str(i % 10) concats | 0.150 / 36 | 0.093 / 66 | 0.145 / 42 | 0.348 / 217 | 0.42x | 0.27x |
old_b6_dict_str | 2.5M random 4-char word counts in a dict + string splitting/replacing | 2.556 / 12 | 0.389 / 47 | 1.688 / 20 | 7.120 / 2585 | 0.24x | 0.05x |
features | Dynamic Python stress test: match/case, except*, yield from, closures, *args/**kwargs, generics, with, dicts/sets | 1.135 / 12 | 0.487 / 42 | 0.954 / 42 | 5.483 / 360 | 0.17x | 0.09x |
The gap between the top and bottom of that table tells you exactly where rcuddle is right now:
- Where World A kicks in: In
old_b4_particles,typed_demo,typed_sim,old_b5_sieve,typed_lists, andarticle, value classes, native lists, and lifted module loops eliminate boxing and GC pressure, beating Nuitka by 10x to 80x and PyPy by 1.4x to 4.2x. Even inshowcase(where startup and frozen stdlib imports take most of the 0.468 s total), it still beats Nuitka by 2.8x. - Where World B still hurts:
old_b3_float_mandelstays boxed at module level because the same module variable switches from int in the first loop to float in the second. Meanwhiletyped_strings,old_b6_dict_str, andfeaturesspend their time in World B dicts, string allocations, or dynamic fallbacks (and in default leak mode,old_b6_dict_strkeeps every temporary string and hits 2.58 GB). Native slim strings, unboxed dicts/sets, and making refcounting the default are what will close that half of the table.
There is more yet to come. I would to talk about it like how gc works,what is unboxing rules,...etc. But that require massiv writing and I barely work on it. So, maybe stay tuned!