Importing Web Assembly (WASM/WAT) in Python using wasmtime

Shobhit chaturvedi
2 min readApr 11, 2023

--

web assembly is assembly binary generated from code written in any programming language (Rust, C++, Go, Python etc.).

assembly binary generated called wasm , wasm file can be generated from any programming language and can be imported to any other programming languages, also it can be run in any host operating system independent of OS at which wasm was generated.

wasm binary can be converted to wat which is human readable text format. we can also write wat file then import and execute in the same way as wasm.

wasm/wat requires wasm runtime to be executed on host os, there are various wasm run time available e.g. wasmtime, wasmer, wasmedge etc.

Here I will be showcasing how we can import wasm/wat in python using wasmtime, lets start —

  1. pip install wasmtime
  2. create wat file or generate it from code written in Rust (or C++, Python, Go).
  3. fib_manual.wat
(module
(func $fib (param $n i32) (result i32)
(if (result i32)
(i32.lt_s (local.get $n)
(i32.const 2))
(then (local.get $n))
;; recursive branch spawns _two_ calls to $fib; not ideal
(else (i32.add (call $fib (i32.sub (local.get $n)
(i32.const 1)))
(call $fib (i32.sub (local.get $n)
(i32.const 2)))))))

(export "fib" (func $fib)))

Or lib.rs (create rust project wasm_lib and update lib.rs with following code)

pub extern "C" fn fib(n:i32) -> i32 {
if n<2{
return n;
}
return fib(n-1)+fib(n-2);
}

generate wasm_lib.wasm from lib.rs, to be able to run below command and generate wasm we need to install wasmtime follow https://docs.wasmtime.dev/cli-install.html

cargo wasi build
//this will generate wasm file under ./target/wasm2wat/debug folder
// we can generate in release as well using --release option

convert wat file using wasm2wat or use wasm file directly in python.

4. load wasm/wat in python test_wasm.py

import wasmtime.loader
import sys
sys.path.append(".")
sys.path.append("target\wasm32-wasi\debug") #add path of wasm module
import fib_manual #use manual wat file in python
import wasm_lib #import wasm module generate from rust
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--num', type=int, required=True)
args = parser.parse_args()
fib_wasm = wasm_lib.fib(args.num)
print("from wasm fibonachi of",args.num," is:",fib_wasm)

fib_wat = fib_manual.fib(args.num)
print("from wat fibonachi of",args.num," is:",fib_wat)

5. Run python

python .\test_wasm.py --num 6

6. Output

from wasm fibonachi of 6is 8
from wat fibonachi of 6is 8

--

--