Skip to content

Commit

Permalink
Merge pull request #375 from ngoldbaum/setitem-fix
Browse files Browse the repository at this point in the history
Add `__setitem__` implementation
  • Loading branch information
neutrinoceros committed Feb 23, 2023
1 parent cc3f451 commit 2ab7b7b
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
5 changes: 5 additions & 0 deletions unyt/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -1728,6 +1728,11 @@ def __getitem__(self, item):
pass
return ret

def __setitem__(self, item, value):
if hasattr(value, "units") and value.units != self.units:
value = value.to(self.units)
super().__setitem__(item, value)

def __pow__(self, p, mod=None, /):
"""
Power function, over-rides the ufunc as
Expand Down
15 changes: 15 additions & 0 deletions unyt/tests/test_unyt_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -2745,3 +2745,18 @@ def test_int8_comparison():
# see regression https://github.com/yt-project/unyt/issues/369
a = unyt_array(np.zeros(5, dtype=np.int8))
assert all(e == 0 for e in a)


def test_setitem():
# see https://github.com/yt-project/unyt/issues/373
a = [1, 2, 3] * cm
a[1] = 2 * m
assert a[1].value == 200
assert a[1].units == cm

with pytest.raises(UnitConversionError):
a[1] = 2 * g

a[1] = 2
assert a[1].value == 2
assert a[1].units == cm

0 comments on commit 2ab7b7b

Please sign in to comment.