Skip to content

Commit d36bc85

Browse files
antonwolfyvtavana
authored andcommitted
Implement dpnp.ndarray.__iter__ method (#2206)
The PR proposes to add implementation of `dpnp.ndarray.__iter__` method. The new code is assumed to be covered by third party tests. - [x] Have you provided a meaningful PR description? - [ ] Have you added a test, reproducer or referred to issue with a reproducer? - [x] Have you tested your changes locally for CPU and GPU devices? - [x] Have you made sure that new changes do not introduce compiler warnings? - [ ] Have you checked performance impact of proposed changes? - [ ] If this PR is a work in progress, are you filing the PR as a draft?
1 parent fbc9529 commit d36bc85

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

dpnp/dpnp_array.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -434,7 +434,11 @@ def __isub__(self, other):
434434
dpnp.subtract(self, other, out=self)
435435
return self
436436

437-
# '__iter__',
437+
def __iter__(self):
438+
"""Return ``iter(self)``."""
439+
if self.ndim == 0:
440+
raise TypeError("iteration over a 0-d array")
441+
return (self[i] for i in range(self.shape[0]))
438442

439443
def __itruediv__(self, other):
440444
"""Return ``self/=value``."""
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import unittest
2+
3+
import numpy
4+
import pytest
5+
6+
import dpnp as cupy
7+
from dpnp.tests.third_party.cupy import testing
8+
9+
10+
@testing.parameterize(
11+
*testing.product(
12+
{"shape": [(3,), (2, 3, 4), (0,), (0, 2), (3, 0)]},
13+
)
14+
)
15+
class TestIter(unittest.TestCase):
16+
17+
@testing.for_all_dtypes()
18+
@testing.numpy_cupy_array_equal()
19+
def test_list(self, xp, dtype):
20+
x = testing.shaped_arange(self.shape, xp, dtype)
21+
return list(x)
22+
23+
@testing.for_all_dtypes()
24+
@testing.numpy_cupy_equal()
25+
def test_len(self, xp, dtype):
26+
x = testing.shaped_arange(self.shape, xp, dtype)
27+
return len(x)
28+
29+
30+
class TestIterInvalid(unittest.TestCase):
31+
32+
@testing.for_all_dtypes()
33+
def test_iter(self, dtype):
34+
for xp in (numpy, cupy):
35+
x = testing.shaped_arange((), xp, dtype)
36+
with pytest.raises(TypeError):
37+
iter(x)
38+
39+
@testing.for_all_dtypes()
40+
def test_len(self, dtype):
41+
for xp in (numpy, cupy):
42+
x = testing.shaped_arange((), xp, dtype)
43+
with pytest.raises(TypeError):
44+
len(x)

0 commit comments

Comments
 (0)