colour.utilities.cast_non_ndarray#

colour.utilities.cast_non_ndarray(a: ArrayLike, dtype: Any) Any | None[source]#

Cast the specified non-numpy.ndarray array \(a\) to the specified numpy.dtype in its native namespace.

This is the Array API sibling of as_ndarray(); it preserves a non-NumPy array’s namespace and device while applying a dtype change via xp_astype(), returning None when the input is a NumPy array, when Array API dispatch is disabled, when the input is not an array (no dtype attribute), or when the namespace does not expose an equivalent dtype.

Parameters:
  • a (ArrayLike) – Array to cast. Returned as-is when its dtype already matches the target.

  • dtype (Any) – Target numpy.dtype. Resolved against the input’s native namespace via attribute lookup on the dtype name.

Returns:

Cast array in its native namespace, or None when the input is not eligible for a non-NumPy cast.

Return type:

object or None

Examples

>>> import numpy as np
>>> cast_non_ndarray(np.array([1, 2, 3]), np.float32) is None
True

Cast a PyTorch tensor while preserving its device:

>>> import torch
>>> set_array_api_enabled(True)
>>> cast_non_ndarray(torch.tensor([1, 2, 3]), np.float32).dtype
torch.float32
>>> set_array_api_enabled(False)