Wasmer Python
Wasmer is a comprehensive WebAssembly runtime for Python, allowing developers to execute WebAssembly binaries securely and efficiently within Python applications. It compiles Wasm modules into native code for near-native performance. The current version, 1.1.0, was released in January 2022, and the project is actively maintained with ongoing developments, including features for Wasmer Edge.
Warnings
- breaking The API underwent a complete rewrite between versions 0.x and 1.0.0 to better align with the core Wasmer runtime API. Code written for 0.x will not be compatible with 1.x without significant changes.
- gotcha The `wasmer` package itself ships with headless engines but no compilers by default. To compile WebAssembly modules, you *must* install a separate compiler package like `wasmer_compiler_cranelift` or `wasmer_compiler_llvm`. If no compiler is installed, compilation will fail.
- gotcha Memory access patterns changed and improved. Older methods for memory views could be less performant. For faster read/write operations on WebAssembly memory, use the `Memory.buffer` getter which implements the Python buffer protocol.
- gotcha Deploying Python applications to Wasmer Edge (a serverless WebAssembly platform) is currently in Beta. While actively developed, users might encounter 'rough edges' or unexpected behavior with complex projects.
Install
-
pip install wasmer wasmer_compiler_cranelift -
pip install wasmer wasmer_compiler_llvm
Imports
- Store
from wasmer import Store
- Module
from wasmer import Module
- Instance
from wasmer import Instance
- engine
from wasmer import engine
- wat2wasm
from wasmer import wat2wasm
Quickstart
from wasmer import Store, Module, Instance
from wasmer_compiler_cranelift import Compiler
from wasmer import engine
# Create a Wasmer Store, which holds the engine and compiler
store = Store(engine.JIT(Compiler))
# Define a WebAssembly module in WAT (WebAssembly Text Format)
wasm_module_wat = """
(module
(type (func (param i32 i32) (result i32)))
(func (export "sum") (type 0) (param i32) (param i32) (result i32)
local.get 0
local.get 1
i32.add)
)
"""
# Compile the module
module = Module(store, wasm_module_wat)
# Instantiate the module
instance = Instance(module)
# Call the exported 'sum' function
result = instance.exports.sum(5, 37)
print(f"The sum is: {result}") # Expected: 42