8000 Merge pull request #5106 from juliantaylor/sequence-fix · numpy/numpy@5554488 · GitHub
[go: up one dir, main page]

Skip to content

Commit 5554488

Browse files
committed
Merge pull request #5106 from juliantaylor/sequence-fix
BUG: check if object provides len() before trying to iterate it
2 parents 04d507f + 8bf9a18 commit 5554488

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

numpy/core/src/multiarray/common.c

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -518,12 +518,20 @@ PyArray_DTypeFromObjectHelper(PyObject *obj, int maxdims,
518518
return 0;
519519
}
520520

521+
/*
522+
* fails if convertable to list but no len is defined which some libraries
523+
* require to get object arrays
524+
*/
525+
size = PySequence_Size(obj);
526+
if (size < 0) {
527+
goto fail;
528+
}
529+
521530
/* Recursive case, first check the sequence contains only one type */
522531
seq = PySequence_Fast(obj, "Could not convert object to sequence");
523532
if (seq == NULL) {
524533
goto fail;
525534
}
526-
size = PySequence_Fast_GET_SIZE(seq);
527535
objects = PySequence_Fast_ITEMS(seq);
528536
common_type = size > 0 ? Py_TYPE(objects[0]) : NULL;
529537
for (i = 1; i < size; ++i) {

numpy/core/tests/test_multiarray.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -636,6 +636,20 @@ def __getitem__(self, index):
636636
assert_(a.dtype == np.dtype(object))
637637
assert_raises(ValueError, np.array, [Fail()])
638638

639+
def test_no_len_object_type(self):
640+
# gh-5100, want object array from iterable object without len()
641+
class Point2:
642+
def __init__(self):
643+
pass
644+
645+
def __getitem__(self, ind):
646+
if ind in [0, 1]:
647+
return ind
648+
else:
649+
raise IndexError()
650+
d = np.array([Point2(), Point2(), Point2()])
651+
assert_equal(d.dtype, np.dtype(object))
652+
639653

640654
class TestStructured(TestCase):
641655
def test_subarray_field_access(self):

0 commit comments

Comments
 (0)
0