IMPORTANT: To view this page as Markdown, append `.md` to the URL (e.g. /docs/manual/basics.md). For the complete Mojo documentation index, see llms.txt.
Skip to main content
Version: Nightly
For the complete Mojo documentation index, see llms.txt. Markdown versions of all pages are available by appending .md to any URL (e.g. /docs/manual/basics.md).

from_numpy_array

def from_numpy_array[mut: Bool, //, dtype: DType, origin: Origin[mut=mut]](ref[origin] array: PythonObject) -> Span[Scalar[dtype], origin]

Borrows a 1-D C-contiguous NumPy array as a Mojo Span.

The returned span aliases the NumPy array's buffer; no bytes are copied. Its origin is tied to array, so the compiler keeps array alive for as long as the span is used; you must still not resize or reallocate array while the span is in use, or the span will dangle. Only pass arrays whose buffer is owned by NumPy (or another Python object).

The borrow follows the mutability of the array reference: an immutable (read) reference yields a read-only span. A mutable reference yields a mutable span, so writes are visible to NumPy and vice versa. Creating a mutable span fails if the underlying NumPy array is not writable. Pass array as an immutable reference to avoid this error.

Example:

from std.python import Python
from std.python.numpy import from_numpy_array

var np = Python.import_module("numpy")
var array = np.arange(8, dtype="float64")
var span = from_numpy_array[DType.float64](array)
var total = Float64(0)
for value in span:
total += value

Constraints:

dtype must be one of the fixed-width numeric dtypes supported by NumPy.

Parameters:

  • mut (Bool): The mutability of the borrow, inferred from array.
  • dtype (DType): The expected element dtype of the array.
  • origin (Origin[mut=mut]): The origin of the borrow, inferred from array.

Args:

  • array (PythonObject): A 1-D, C-contiguous NumPy ndarray whose dtype matches dtype.

Returns:

Span[Scalar[dtype], origin]: A Span of length array.size viewing the array's buffer, with the same mutability and origin as the array binding.

Raises:

If array is not 1-D, is not C-contiguous, has a dtype that does not match dtype, or is not writable when borrowed mutably.