Rust & Wasm: Load Wasm modules in Python

Neo Quest | Nikhil Gupta

Neo Quest | Nikhil Gupta / January 29, 2023

2 min read


In the previous article, we embedded Wasmtime in a Rust CLI to dynamically load Wasm modules. This article will load our wasm modules in Python using Wasmtime's Python integration.

Create a demo wasm module: Quick Recap

Similar to the previous article, let's first create a basic wasm module that will expose a simple function to add two numbers, which we will later load in our python script.

Let's first create a new library like so:

cargo new demo-wasm --lib

and modify the type in Cargo.toml:


+crate-type = ["cdylib", "rlib"]

Next, let's modify our to expose the function:

pub extern "C" fn add(left: u32, right: u32) -> u32 {
    left + right

Finally, let's build our wasm:

cargo build --target wasm32-wasi --release

As expected, we are targeting wasi, a modular interface for WebAssembly which is implemented by Wasmtime, that provides access to OS-like-features, including files, etc.

Install wasmtime package

Now, we will simply use pip package manager to install wasmtime like so:

pip install wasmtime

Load wasm module in python

Next, let's create a python script and copy the demo_wasm to the same folder. Finally, let's use the wasmtime.loader to load our wasm module.

import wasmtime.loader
import demo_wasm

Call wasm module from python

Now, we should have all our exposed functions directly available in python. Let's call our add function like so:

print(demo_wasm.add(1, 2))

Now, if you run the updated app, you should see 3 printed on the terminal :) In this way, we can load any Wasm module into our Python app!

If you liked this article, subscribe here to get the complete code and updates for the entire collection: Rust & Wasm.