1 · Write Python
def fibonacci(n: int) -> int:
if n <= 1:
return n
a, b = 0, 1
for i in range(2, n + 1):
a, b = b, a + b
return b
def factorial(n: int) -> int:
result = 1
for i in range(1, n + 1):
result *= i
return result
Ordinary, type-annotated Python is the compiler's input. Annotations pick the WASM value types: int and bool become i32, float becomes f64.
2 · Compile from Rust
use waspy::compile_python_file;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let wasm =
compile_python_file("fibonacci.py", true)?;
std::fs::write("fibonacci.wasm", &wasm)?;
Ok(())
}
cargo run turns fibonacci.py into fibonacci.wasm. Every top-level Python function becomes a WASM export, and imports of sibling .py files link in automatically.
3 · Run from JS or TS
import { readFile } from "node:fs/promises";
const wasm = await readFile("./fibonacci.wasm");
const { instance } =
await WebAssembly.instantiate(wasm);
console.log(instance.exports.fibonacci(10));
console.log(instance.exports.factorial(5));
node run.mjs prints 55 and 120: your Python, running as WebAssembly. In a browser, swap readFile for fetch and WebAssembly.instantiateStreaming.