Skip to content

Commit f832c62

Browse files
committed
Add explicit checks to disallow size with any boolean item
1 parent 97542d3 commit f832c62

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

dpnp/dpnp_utils/dpnp_algo_utils.pyx

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -390,17 +390,26 @@ cpdef inline tuple _object_to_tuple(object obj):
390390
if obj is None:
391391
return ()
392392

393-
if cpython.PySequence_Check(obj):
393+
# dpnp.ndarray unconditionally succeeds in PySequence_Check as it implements __getitem__
394+
if cpython.PySequence_Check(obj) and not dpnp.is_supported_array_type(obj):
395+
if isinstance(obj, numpy.ndarray):
396+
obj = numpy.atleast_1d(obj)
397+
394398
nd = len(obj)
395399
shape = []
396400

397401
for i in range(0, nd):
402+
if cpython.PyBool_Check(obj[i]):
403+
raise TypeError("DPNP object_to_tuple(): no item in size can be bool")
404+
398405
# Assumes each item is castable to Py_ssize_t,
399406
# otherwise TypeError will be raised
400407
shape.append(<Py_ssize_t> obj[i])
401408
return tuple(shape)
402409

403410
if dpnp.isscalar(obj):
411+
if cpython.PyBool_Check(obj):
412+
raise TypeError("DPNP object_to_tuple(): 'obj' can't be bool")
404413
return (obj, )
405414

406415
raise ValueError("DPNP object_to_tuple(): 'obj' should be 'None', collections.abc.Sequence, or 'int'")

dpnp/tests/test_random_state.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1125,3 +1125,17 @@ def test_size_castable_to_integer(self):
11251125
for size in sizes:
11261126
result = RandomState().uniform(size=size)
11271127
assert result.shape == size
1128+
1129+
@pytest.mark.parametrize("xp", [numpy, dpnp])
1130+
@pytest.mark.parametrize("size", [True, [True], dpnp.bool(True), numpy.array(True), numpy.array([True])])
1131+
def test_bool_size(self, xp, size):
1132+
rs = xp.random.RandomState()
1133+
assert_raises(TypeError, rs.uniform, size=size)
1134+
1135+
@pytest.mark.parametrize("size", [numpy.array(1), numpy.array([2])])
1136+
def test_numpy_ndarray_size(self, size):
1137+
result = RandomState().uniform(size=size)
1138+
assert result.shape == size
1139+
1140+
def test_dpnp_ndarray_size(self):
1141+
assert_raises(ValueError, RandomState().uniform, size=dpnp.array(1))

0 commit comments

Comments
 (0)