Skip to content

Commit 39af026

Browse files
authored
gh-161840: Propagate __len__ exceptions in ctypes array slice assignment (GH-161859)
1 parent 9c0a545 commit 39af026

3 files changed

Lines changed: 35 additions & 0 deletions

File tree

‎Lib/test/test_ctypes/test_slicing.py‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,35 @@ def test_setslice_cint(self):
6363
with self.assertRaises(ValueError):
6464
a[:5] = range(32)
6565

66+
def test_setslice_len_error(self):
67+
# gh-161840: exceptions from PySequence_Length() must propagate
68+
# instead of being replaced with ValueError.
69+
class CustomError(Exception):
70+
pass
71+
72+
class BadLen:
73+
def __len__(self):
74+
raise CustomError("boom")
75+
76+
class BadValueErrorLen:
77+
def __len__(self):
78+
raise ValueError("custom value error")
79+
80+
a = (c_int * 3)(1, 2, 3)
81+
with self.assertRaisesRegex(CustomError, "boom"):
82+
a[0:1] = BadLen()
83+
with self.assertRaisesRegex(CustomError, "boom"):
84+
a[0:0] = BadLen()
85+
with self.assertRaisesRegex(CustomError, "boom"):
86+
a[::2] = BadLen()
87+
with self.assertRaisesRegex(ValueError, "custom value error"):
88+
a[0:1] = BadValueErrorLen()
89+
with self.assertRaisesRegex(TypeError, "object of type 'int' has no len"):
90+
a[0:1] = 42
91+
with self.assertRaisesRegex(TypeError, "dict is not a sequence"):
92+
a[0:1] = {"x": 1}
93+
self.assertEqual(a[:], [1, 2, 3])
94+
6695
def test_char_ptr(self):
6796
s = b"abcdefghijklmnopqrstuvwxyz"
6897

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Propagate exceptions raised while getting the length of the assigned value
2+
in :mod:`ctypes` array slice assignment instead of replacing them with a
3+
:exc:`ValueError`.

‎Modules/_ctypes/_ctypes.c‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5373,6 +5373,9 @@ Array_ass_subscript_impl(PyObject *myself, PyObject *item, PyObject *value)
53735373
stop = start;
53745374

53755375
otherlen = PySequence_Length(value);
5376+
if (otherlen < 0) {
5377+
return -1;
5378+
}
53765379
if (otherlen != slicelen) {
53775380
PyErr_SetString(PyExc_ValueError,
53785381
"Can only assign sequence of same size");

0 commit comments

Comments
 (0)