Skip to content
Closed
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
11 changes: 11 additions & 0 deletions numpy/_core/src/multiarray/array_coercion.c
Original file line number Diff line number Diff line change
Expand Up @@ -1197,6 +1197,17 @@ PyArray_DiscoverDTypeAndShape_Recursive(
copy = -1;
}

/* Check for self-nested sequences to prevent RAM exhaustion */
if (is_sequence) {
if (PySequence_Check(objects[0])) {
if (objects[0] == obj) {
Copy link
Member

@jorenham jorenham Aug 25, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this still leaves

l = [[]]
l[0].append(l)
l[0].append(l)
np.array(l)

and 62 other cases like these

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(not that that's necessarily a problem, it's just something to be aware of)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I got u, this addresses only one specific and most common case of self-nesting. Thanks !

PyErr_SetString(PyExc_ValueError,
"NumPy array cannot be created using self-nested sequences.");
return -1;
}
}
}

/* Recursive call for each sequence item */
for (Py_ssize_t i = 0; i < size; i++) {
max_dims = PyArray_DiscoverDTypeAndShape_Recursive(
Expand Down
11 changes: 7 additions & 4 deletions numpy/_core/tests/test_array_coercion.py
Original file line number Diff line number Diff line change
Expand Up @@ -505,12 +505,15 @@ def test_pathological_self_containing(self):
# Test that this also works for two nested sequences
l = []
l.append(l)
arr = np.array([l, l, l], dtype=object)
assert arr.shape == (3,) + (1,) * (ncu.MAXDIMS - 1)

with pytest.raises(ValueError, match="cannot be created using self-nested"):
arr = np.array([l, l, l], dtype=object)
# assert arr.shape == (3,) + (1,) * (ncu.MAXDIMS - 1)

# Also check a ragged case:
arr = np.array([l, [None], l], dtype=object)
assert arr.shape == (3, 1)
with pytest.raises(ValueError, match="cannot be created using self-nested"):
arr = np.array([l, [None], l], dtype=object)
# assert arr.shape == (3, 1)

@pytest.mark.parametrize("arraylike", arraylikes())
def test_nested_arraylikes(self, arraylike):
Expand Down
Loading