WebAssembly Python, Honestly
Python does not compile to WebAssembly directly. A runtime carries Python into the browser instead.
Run Python with Pyodide
Load Pyodide, then run one Python line.
const pyodide = await loadPyodide();
const result = pyodide.runPython("2 + 3");
console.log(result);Define add in Python
This Python function runs inside the runtime.
def add(a, b):
return a + bExample
const B64 = "AGFzbQEAAAABBwFgAn9/AX8DAgEABwcBA2FkZAAACgkBBwAgACABags=";
(async () => {
const bytes = Uint8Array.from(atob(B64), c => c.charCodeAt(0));
const { instance } = await WebAssembly.instantiate(bytes, {});
console.log("2 + 3 =", instance.exports.add(2, 3));
})();Key points
- Interpreter: a program that runs code line by line, instead of compiling it first.
- Python runs on an interpreter, not a compiler.
- Pyodide embeds CPython in WebAssembly for the browser.
- The Pyodide runtime is about 10 MB or more.
- MicroPython is a smaller runtime for small scripts.
- Boot stays slow when the runtime is large.
- Python in the browser suits data work and teaching.
- The demo module below is the same add function compiled from WAT.
- Python reaches Wasm through a runtime, not a direct compile.
In this example, the code decodes the module bytes from B64 and instantiates the module. It calls add with 2 and 3 and logs the sum. Python itself is not compiled here.
Note
The browser caches the runtime, so later visits load fast.
Try it Yourself
Edit the code, then press Run.
Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
How does Python run in the browser?