Mojo does not yet have a built-in bridge that can read a NumPy array that lives in CPython from Mojo code.
Therefore the only practical way today is to copy the data out of the ndarray in Python, hand the raw buffer to Mojo, and then build a Mojo List (or Tensor, NDBuffer, …) from that buffer.
Below are two complete patterns that work with the current Mojo 0.8.x/0.9.x toolchain.
- Copy through a Python object (works in a Mojo REPL or notebook)
from python import Python
from tensor import Tensor, TensorShape
from algorithm import vectorize
fn ndarray_to_mojo_list(py_nd: PythonObject) raises -> List[Float32]:
"""
py_nd is expected to be a NumPy ndarray with dtype float32.
Returns a flat Mojo List[Float32].
"""
# 1. Make sure we really have a NumPy array
np = Python.import_module("numpy")
if not py_nd.isinstance(np.ndarray):
raise Error("Expected a numpy.ndarray")
# 2. Ensure C-contiguous float32
let arr = np.ascontiguousarray(py_nd.astype(np.float32))
# 3. Get raw bytes
let buf = arr.tobytes() # Python bytes object
let ptr = buf.__buffer__() # Python buffer protocol
let size = int(ptr.nbytes / 4) # 4 bytes per float32
# 4. Copy into a Mojo List
var out = List[Float32]()
out.reserve(size)
for i in range(size):
# reinterpret bytes as float32
let val = ptr[i * 4].bitcast[DType.float32]
out.append(val)
return out
Usage from a Mojo cell:
let np = Python.import_module("numpy")
let a = np.array([[1.0, 2.0], [3.0, 4.0]], dtype="float32")
let mojo_list = ndarray_to_mojo_list(a)
print(mojo_list) # List([1.0, 2.0, 3.0, 4.0])
- Write the array to disk and read it from Mojo
If you are running Mojo as a compiled binary (not inside a Python REPL), the simplest route is to dump the array in a format Mojo can read (raw binary, NPY, or CSV) and then read it back.
Python side (run once):
import numpy as np
a = np.arange(12, dtype=np.float32).reshape(3, 4)
a.tofile("a.bin") # raw little-endian float32
Mojo side:
import sys
from memory import Buffer
from tensor import Tensor, TensorShape
from algorithm import vectorize
fn main() raises:
let buf = Buffer.read_from_file("a.bin") # Buffer of bytes
let size = buf.size / 4 # float32
var data = List[Float32]()
data.reserve(size)
for i in range(size):
let val = buf.load[width=4](i * 4).bitcast[DType.float32]
data.append(val)
print(data) # List([0.0, 1.0, 2.0, ..., 11.0])
Key points / limitations
- There is currently no zero-copy view of a NumPy array from Mojo.
- The PythonObject bridge only works when Mojo itself is running inside CPython (REPL, Jupyter, or
mojo run).
- If you need the data as a multidimensional
Tensor instead of a flat List, build the Tensor from the same buffer and supply the shape manually.
Until the Mojo team ships a dedicated numpy interop module, one of the two patterns above is the recommended workflow.