Skip to content

p2w: Python to WebAssembly

p2w is an ahead-of-time compiler from a substantial subset of Python to WebAssembly. It translates Python source to WebAssembly text (WAT), which wasm-tools assembles into a module that runs in Node.js or in a browser. Memory is managed by WebAssembly GC: every Python object is a GC struct or array on the host engine's heap, so p2w ships no garbage collector of its own.

$ cat fib.py
def fib(n):
    a, b = 0, 1
    for _ in range(n):
        a, b = b, a + b
    return a

print(fib(30))
$ uv run p2w -r fib.py
832040

What it compiles

Classes with inheritance, properties and special methods; closures, decorators, lambdas, keyword and *args/**kwargs parameters; generators, yield from and comprehensions; try/except/finally, exception chaining and with; match statements; f-strings and str.format; lists, tuples, dicts, sets, strings and bytes with most of their methods; import math. The Supported Python page has the details.

p2w checks itself against CPython: 102 of the 104 test programs in programs/internal/ print exactly what CPython prints, and the test suite runs every one of them under both. What p2w cannot compile faithfully, it refuses at compile time with an error naming the construct, rather than producing a program that runs and prints a wrong answer. The known bugs page lists both the refusals and the few things that still compile and misbehave.

How fast

Without type annotations, a compiled program runs at roughly CPython's speed: every value is a boxed reference. With annotations, the compiler keeps numbers in unboxed WebAssembly locals, and the benchmark suite runs at a geometric mean of 9.13× CPython (2026-10-08), from 2.1× on nbody to 127× on fibonacci. See Performance and native types.

Where to go next

Prior art

p2w was inspired by Bob, Eli Bendersky's Scheme interpreter and compiler, and unblocked by his Compiling Scheme to WebAssembly. Earlier attempts in the same family are Compylo, started by Ethan Zouzoulkowsky at EPITA in 2023, and Prescrypt, a Python-to-JavaScript compiler based on PScript.

p2w is released under the MIT license.