Skip to content

Commit 3f737be

Browse files
authored
Add dpnp.iterable function (#2208)
There was `__iter__` method of dpnp.ndarray implemented in scope of #2206. While this PR proposes to add implementation of `dpnp.iterable` function which is intended to check if the object (including dpnp.ndarray) can be iterated over. The implementation leverages on NumPy call, which is based on attempt to pass the object to `iter` function.
1 parent ed39ea7 commit 3f737be

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

dpnp/dpnp_iface_indexing.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@
6969
"fill_diagonal",
7070
"flatnonzero",
7171
"indices",
72+
"iterable",
7273
"ix_",
7374
"mask_indices",
7475
"ndindex",
@@ -1033,6 +1034,47 @@ def indices(
10331034
return res
10341035

10351036

1037+
def iterable(y):
1038+
"""
1039+
Check whether or not an object can be iterated over.
1040+
1041+
For full documentation refer to :obj:`numpy.iterable`.
1042+
1043+
Parameters
1044+
----------
1045+
y : object
1046+
Input object.
1047+
1048+
Returns
1049+
-------
1050+
out : bool
1051+
Return ``True`` if the object has an iterator method or is a sequence
1052+
and ``False`` otherwise.
1053+
1054+
Examples
1055+
--------
1056+
>>> import dpnp as np
1057+
>>> np.iterable([1, 2, 3])
1058+
True
1059+
>>> np.iterable(2)
1060+
False
1061+
1062+
In most cases, the results of ``np.iterable(obj)`` are consistent with
1063+
``isinstance(obj, collections.abc.Iterable)``. One notable exception is
1064+
the treatment of 0-dimensional arrays:
1065+
1066+
>>> from collections.abc import Iterable
1067+
>>> a = np.array(1.0) # 0-dimensional array
1068+
>>> isinstance(a, Iterable)
1069+
True
1070+
>>> np.iterable(a)
1071+
False
1072+
1073+
"""
1074+
1075+
return numpy.iterable(y)
1076+
1077+
10361078
def ix_(*args):
10371079
"""Construct an open mesh from multiple sequences.
10381080

dpnp/tests/test_indexing.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -337,6 +337,14 @@ def test_ix_error(self, xp, shape):
337337
assert_raises(ValueError, xp.ix_, xp.ones(shape))
338338

339339

340+
class TestIterable:
341+
@pytest.mark.parametrize("data", [[1.0], [2, 3]])
342+
def test_basic(self, data):
343+
a = numpy.array(data)
344+
ia = dpnp.array(a)
345+
assert dpnp.iterable(ia) == numpy.iterable(a)
346+
347+
340348
@pytest.mark.parametrize(
341349
"shape", [[1, 2, 3], [(1, 2, 3)], [(3,)], [3], [], [()], [0]]
342350
)

0 commit comments

Comments
 (0)