DEV Community

Ajeet Singh Raina
Ajeet Singh Raina

Posted on

Using WebAssembly with Python

Here's a simple example of using WebAssembly (Wasm) with Python:

Create a simple Wasm module using a language like C or Rust. For this example, let's use a C program that calculates the square of a number:

// square.c

int square(int num) {
    return num * num;
}
Enter fullscreen mode Exit fullscreen mode

Compile the C code into a Wasm module using Emscripten or another suitable compiler:

emcc square.c -o square.wasm
Enter fullscreen mode Exit fullscreen mode

Now, let's use Python to load and run the Wasm module. Install the wasmtime Python package, which provides a runtime for executing Wasm modules:

pip install wasmtime
Enter fullscreen mode Exit fullscreen mode

Write a Python script that loads and executes the Wasm module:

# main.py

import wasmtime

# Load the Wasm module
wasm_module = wasmtime.Module.from_file("square.wasm")

# Create an instance of the module
instance = wasmtime.Instance(wasm_module)

# Get a reference to the exported function
square_func = instance.exports.square

# Call the function and print the result
result = square_func(5)
print("Square of 5:", result)
Enter fullscreen mode Exit fullscreen mode

Run the Python script to see the output:

python main.py
Enter fullscreen mode Exit fullscreen mode

The output will be:

Square of 5: 25
Enter fullscreen mode Exit fullscreen mode

In this example, we compiled a C program into a Wasm module and used the wasmtime Python package to load and execute the module. This demonstrates the integration of Wasm with Python, allowing you to leverage the capabilities of other programming languages within your Python applications.

Containerising Wasm + Python

To containerize the Wasm + Python example, we can use Docker. Here's how you can create a Dockerfile to package the application:

Create a file named Dockerfile (without any file extension) in the same directory as your Python script and Wasm module.

Open the Dockerfile and add the following content:

# Use a Python base image
FROM python:3.9

# Set the working directory inside the container
WORKDIR /app

# Copy the Python script and Wasm module into the container
COPY main.py square.wasm ./

# Install the required Python packages
RUN pip install wasmtime

# Run the Python script
CMD ["python", "main.py"]
Enter fullscreen mode Exit fullscreen mode

Save the Dockerfile.

Open a terminal or command prompt, navigate to the directory containing the Dockerfile and other files, and build the Docker image:

docker build -t wasm-python-example .
Enter fullscreen mode Exit fullscreen mode

After the image is built successfully, you can run a container based on the image:

docker run wasm-python-example
Enter fullscreen mode Exit fullscreen mode

Top comments (0)