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.

Available 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.

Usage

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.

Example

Create a new project:

$ spin new http-py python-example --accept-defaults

Take a look at the scaffolded program in app.py:

from spin_http import Response

def handle_request(request):

    return Response(200,
                    {"content-type": "text/plain"},
                    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/"

Serving http://127.0.0.1:3000
Available Routes:
  python-example: http://127.0.0.1:3000 (wildcard)

Test it with curl:

$ curl localhost:3000/
Hello from the Python SDK

The file 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

Learn More

Joel’s video on Spin, Python, and Components:

Here are some great resources: