diff --git a/dpnp/dpnp_array.py b/dpnp/dpnp_array.py index 0ca55e8c315..6456b4b5072 100644 --- a/dpnp/dpnp_array.py +++ b/dpnp/dpnp_array.py @@ -434,7 +434,11 @@ def __isub__(self, other): dpnp.subtract(self, other, out=self) return self - # '__iter__', + def __iter__(self): + """Return ``iter(self)``.""" + if self.ndim == 0: + raise TypeError("iteration over a 0-d array") + return (self[i] for i in range(self.shape[0])) def __itruediv__(self, other): """Return ``self/=value``.""" diff --git a/dpnp/tests/third_party/cupy/core_tests/test_iter.py b/dpnp/tests/third_party/cupy/core_tests/test_iter.py new file mode 100644 index 00000000000..4414d1c8cf4 --- /dev/null +++ b/dpnp/tests/third_party/cupy/core_tests/test_iter.py @@ -0,0 +1,44 @@ +import unittest + +import numpy +import pytest + +import dpnp as cupy +from dpnp.tests.third_party.cupy import testing + + +@testing.parameterize( + *testing.product( + {"shape": [(3,), (2, 3, 4), (0,), (0, 2), (3, 0)]}, + ) +) +class TestIter(unittest.TestCase): + + @testing.for_all_dtypes() + @testing.numpy_cupy_array_equal() + def test_list(self, xp, dtype): + x = testing.shaped_arange(self.shape, xp, dtype) + return list(x) + + @testing.for_all_dtypes() + @testing.numpy_cupy_equal() + def test_len(self, xp, dtype): + x = testing.shaped_arange(self.shape, xp, dtype) + return len(x) + + +class TestIterInvalid(unittest.TestCase): + + @testing.for_all_dtypes() + def test_iter(self, dtype): + for xp in (numpy, cupy): + x = testing.shaped_arange((), xp, dtype) + with pytest.raises(TypeError): + iter(x) + + @testing.for_all_dtypes() + def test_len(self, dtype): + for xp in (numpy, cupy): + x = testing.shaped_arange((), xp, dtype) + with pytest.raises(TypeError): + len(x)