Thanks to visit codestin.com
Credit goes to github.com

Skip to content

BUG: fix __setitem__ for invalid dtype combinations #157

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 20, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
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
9 changes: 9 additions & 0 deletions array_api_strict/_array_object.py
Original file line number Diff line number Diff line change
Expand Up @@ -942,6 +942,15 @@ def __setitem__(
self._validate_index(key, op="setitem")
# Indexing self._array with array_api_strict arrays can be erroneous
np_key = key._array if isinstance(key, Array) else key

# sanitize the value
other = value
if isinstance(value, (bool, int, float, complex)):
other = self._promote_scalar(value)
dt = _result_type(self.dtype, other.dtype)
if dt != self.dtype:
raise TypeError(f"mismatched dtypes: {self.dtype = } and {other.dtype = }")

self._array.__setitem__(np_key, asarray(value)._array)

def __sub__(self, other: Array | complex, /) -> Array:
Expand Down
25 changes: 25 additions & 0 deletions array_api_strict/tests/test_array_object.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,14 @@
_integer_or_boolean_dtypes,
_real_numeric_dtypes,
_numeric_dtypes,
uint8,
int8,
int16,
int32,
int64,
uint64,
float64,
complex128,
bool as bool_,
)
from .._flags import set_array_api_strict_flags
Expand Down Expand Up @@ -193,6 +195,29 @@ def test_indexing_arrays_different_devices():
a[idx1, idx2]


def test_setitem_invalid_promotions():
# Check that violating these two raises:
# Setting array values must not affect the data type of self, and
# Behavior must otherwise follow Type Promotion Rules.
a = asarray([1, 2, 3])
with pytest.raises(TypeError):
a[0] = 3.5

with pytest.raises(TypeError):
a[0] = asarray(3.5)

a = asarray([1, 2, 3], dtype=uint8)
with pytest.raises(TypeError):
a[0] = asarray(42, dtype=uint64)

a = asarray([1, 2, 3], dtype=float64)
with pytest.raises(TypeError):
a[0] = 3.5j

with pytest.raises(TypeError):
a[0] = asarray(3.5j, dtype=complex128)


def test_promoted_scalar_inherits_device():
device1 = Device("device1")
x = asarray([1., 2, 3], device=device1)
Expand Down
Loading