Wasmtime Python Bindings

43.0.0 · active · verified Sun Apr 12

Wasmtime-py provides Python bindings for the Wasmtime project, a fast, secure, and standards-compliant WebAssembly runtime. It allows Python applications to validate, compile, instantiate, and interact with WebAssembly modules, including support for WASI and the Component Model. The library follows the Wasmtime versioning scheme, releasing a new major version monthly, which can include breaking changes. The current version is 43.0.0.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to compile and instantiate a WebAssembly module using `wasmtime-py`. It defines a simple WAT module that imports a host function and exports a function to call it. The Python host function `say_hello` is then bound to the WebAssembly import and executed.

from wasmtime import Store, Module, Instance, Func, FuncType

# Almost all operations in Wasmtime require a contextual 'store' argument.
store = Store()

# Define a simple WebAssembly module in WAT format.
# It imports a 'hello' function and exports a 'run' function that calls 'hello'.
wasm_text = '''
(module
  (func $hello (import "" "hello"))
  (func (export "run") (call $hello))
)
'''

# Compile the module. This step happens once.
module = Module(store.engine, wasm_text)

# Define the Python function that the WebAssembly module will import.
def say_hello():
    print("Hello from Python!")

# Create a Func object from the Python function, specifying its signature.
# Here, it takes no parameters and returns nothing.
hello_func = Func(store, FuncType([], []), say_hello)

# Instantiate the module, providing the necessary imports.
# The `hello_func` is mapped to the `"" "hello"` import.
instance = Instance(store, module, [hello_func])

# Get the exported 'run' function from the WebAssembly module.
run = instance.exports(store)["run"]

# Call the WebAssembly 'run' function.
# This in turn calls the Python `say_hello` function.
run(store)

view raw JSON →