Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions dpnp/dpnp_iface_manipulation.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
"atleast_3d",
"broadcast_arrays",
"broadcast_to",
"can_cast",
"concatenate",
"copyto",
"expand_dims",
Expand Down Expand Up @@ -402,6 +403,38 @@ def broadcast_to(array, /, shape, subok=False):
return dpnp_array._create_from_usm_ndarray(new_array)


def can_cast(from_, to, casting="safe"):
"""
Returns True if cast between data types can occur according to the casting rule.

If `from` is a scalar or array scalar, also returns ``True`` if the scalar value can
be cast without overflow or truncation to an integer.

Parameters
----------
from : dpnp.array, dtype
Source data type.
to : dtype
Target data type.
casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
Controls what kind of data casting may occur.

Returns
-------
out: bool
True if cast can occur according to the casting rule.

"""

if isinstance(to, dpnp_array):
raise TypeError("Expected dtype type")

dtype_from = (
from_.dtype if isinstance(from_, dpnp_array) else dpnp.dtype(from_)
)
return dpt.can_cast(dtype_from, to, casting)


def concatenate(
arrays, /, *, axis=0, out=None, dtype=None, casting="same_kind"
):
Expand Down
11 changes: 11 additions & 0 deletions tests/test_arraymanipulation.py
Original file line number Diff line number Diff line change
Expand Up @@ -928,3 +928,14 @@ def test_subok_error():
with pytest.raises(NotImplementedError):
dpnp.broadcast_arrays(x, subok=True)
dpnp.broadcast_to(x, (4, 4), subok=True)


def test_can_cast():
X = dpnp.ones((2, 2), dtype=dpnp.int64)
pytest.raises(TypeError, dpnp.can_cast, X, 1)
pytest.raises(TypeError, dpnp.can_cast, X, X)

X_np = numpy.ones((2, 2), dtype=numpy.int64)
assert dpnp.can_cast(X, "float32") == numpy.can_cast(X_np, "float32")
assert dpnp.can_cast(X, dpnp.int32) == numpy.can_cast(X_np, numpy.int32)
assert dpnp.can_cast(X, dpnp.int64) == numpy.can_cast(X_np, numpy.int64)