Skip to content

Commit

Permalink
Implement dpnp.ndarray.__iter__ method (#2206)
Browse files Browse the repository at this point in the history
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?
  • Loading branch information
antonwolfy authored and vtavana committed Dec 2, 2024
1 parent 54e0397 commit 781041e
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
6 changes: 5 additions & 1 deletion dpnp/dpnp_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -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``."""
Expand Down
44 changes: 44 additions & 0 deletions dpnp/tests/third_party/cupy/core_tests/test_iter.py
Original file line number Diff line number Diff line change
@@ -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)

0 comments on commit 781041e

Please sign in to comment.