Python in WebAssembly
Python is one of the most popular programming languages in the world, and its WebAssembly implementation seems to be coming along quickly. While it is not yet ready for use, we anticipate it will be functional in the first half of 2022.
The most momentum is in the CPython community, which is approaching both Emscripten-based and WASI-based implementations.
WebAssembly support is officially available in CPython 3.11 and after. The GitHub CPython repo has all of the code.
There is also a Spin SDK for Python that uses CPython, but reduces startup time by preloading and initializing the scripts. There’s a detailed blog post about Python on Fermyon.com that explains this.
The Spin SDK makes it very easy to build Python-based Wasm applications simply by using a Spin template that handles all of the heavy lifting.
Create a new project:
$ spin new http-py python-example --accept-defaults
Take a look at the scaffolded program in
from spin_http import Response
bytes(f"Hello from the Python SDK", "utf-8"))
Compile a Wasm binary with the scripts preloaded, and then start up a local server:
$ spin build --up
Building component python-example with `spin py2wasm app -o app.wasm`
Spin-compatible module built successfully
Finished building all Spin components
Logging component stdio to ".spin/logs/"
python-example: http://127.0.0.1:3000 (wildcard)
Test it with
$ curl localhost:3000/
Hello from the Python SDK
app.wasm contains both the interpreter (in an initialized state) and all of the userland code:
$ ls -lah app.wasm
-rw-r--r-- 1 technosophos staff 24M Oct 26 18:22 app.wasm
Joel’s video on Spin, Python, and Components:
Here are some great resources:
- A tutorial for building Python Wasm apps with Spin
- A tutorial doing AI inferencing with Python and Spin
- The Spin Python SDK
- The Spin Developer Docs fully document the Python SDKs
- Python Wasm examples at Spin Up Hub
- The Componentize-Py tooling
- VMware has a distribution of CPython as Wasm based on official CPython
- A detailed document about the (once) current state and features of Wasm in the latest CPython version (Now outdated)
- Fermyon.com published a slightly more in-depth Python and Wasm tutorial
- An in-browser Python shell in Wasm (Not the preferred path)
- One version of CPython + Wasm, where they are working on WASI support
- SingleStore’s wasi-python project is another approach