8000 BUG: check if object provides len() before trying to iterate it by juliantaylor · Pull Request #5106 · numpy/numpy · GitHub
[go: up one dir, main page]

Skip to content

BUG: check if object provides len() before trying to iterate it #5106

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 23, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
BUG: check if object provides len() before trying to iterate it
some libraries want object arrays from objects that are iterable but
rely on not providing len() to get the right dtype from numpy.
closes gh-5100
  • Loading branch information
juliantaylor committed Sep 23, 2014
commit 8bf9a18f68a36f81bbd27ce52af65ca3cfd217fd
10 changes: 9 additions & 1 deletion numpy/core/src/multiarray/common.c
Original file line number Diff line number Diff line change
Expand Up @@ -518,12 +518,20 @@ PyArray_DTypeFromObjectHelper(PyObject *obj, int maxdims,
return 0;
}

/*
* fails if convertable to list but no len is defined which some libraries
* require to get object arrays
*/
size = PySequence_Size(obj);
if (size < 0) {
goto fail;
}

/* Recursive case, first check the sequence contains only one type */
seq = PySequence_Fast(obj, "Could not convert object to sequence");
if (seq == NULL) {
goto fail;
}
size = PySequence_Fast_GET_SIZE(seq);
objects = PySequence_Fast_ITEMS(seq);
common_type = size > 0 ? Py_TYPE(objects[0]) : NULL;
for (i = 1; i < size; ++i) {
Expand Down
14 changes: 14 additions & 0 deletions numpy/core/tests/test_multiarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -593,6 +593,20 @@ def __getitem__(self, index):
assert_(a.dtype == np.dtype(object))
assert_raises(ValueError, np.array, [Fail()])

def test_no_len_object_type(self):
# gh-5100, want object array from iterable object without len()
class Point2:
def __init__(self):
pass

def __getitem__(self, ind):
if ind in [0, 1]:
return ind
else:
raise IndexError()
d = np.array([Point2(), Point2(), Point2()])
assert_equal(d.dtype, np.dtype(object))


class TestStructured(TestCase):
def test_subarray_field_access(self):
Expand Down
0