Wasmtime Python Bindings
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
- breaking Wasmtime-py releases a new major version monthly, and these new versions can introduce breaking changes to the API and behavior. Users should regularly update their dependency requirements.
- breaking Version 43.0.0 of `wasmtime` (the underlying Rust crate) has a use-after-free bug when cloning a `wasmtime::Linker` object. This can lead to segfaults if the original linker instance is dropped and then the cloned instance is used. The Python bindings are affected if they expose or implicitly use this unsound cloning behavior.
- gotcha Calling small WebAssembly functions from Python using `wasmtime-py` incurs a noticeable performance overhead (approximately 30μs per call in benchmarks). This is due to the overhead of interop between Python and the underlying Wasmtime C API.
- gotcha Python bindings for Wasmtime are built on the C API and developed externally from the main Wasmtime repository. This means that updates and new features in `wasmtime-py` may lag behind the core Wasmtime project's Rust and C APIs.
Install
-
pip install wasmtime
Imports
- Store
from wasmtime import Store
- Module
from wasmtime import Module
- Instance
from wasmtime import Instance
- Func
from wasmtime import Func
- FuncType
from wasmtime import FuncType
Quickstart
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)