From 3369ee57ad730cf6f4449cf459c25b77fb765b1c Mon Sep 17 00:00:00 2001 From: Yusuke Hayashi Date: Mon, 23 Nov 2026 06:42:32 +0900 Subject: [PATCH] gh-161840: Propagate `__len__` exceptions in ctypes array slice assignment (GH-161859) (cherry picked from commit 39af0268ee92d4837cd0c2f80eaa2d5759a87f14) Co-authored-by: Yusuke Hayashi --- Lib/test/test_ctypes/test_slicing.py | 29 +++++++++++++++++++ ...-11-12-08-38-09.gh-issue-161840.YcEVjO.rst | 3 ++ Modules/_ctypes/_ctypes.c | 3 ++ 3 files changed, 35 insertions(+) create mode 100644 Misc/NEWS.d/next/Library/2026-11-12-08-38-09.gh-issue-161840.YcEVjO.rst diff --git a/Lib/test/test_ctypes/test_slicing.py b/Lib/test/test_ctypes/test_slicing.py index 66f9e530104cac..b8c981ca2b17fa 100644 --- a/Lib/test/test_ctypes/test_slicing.py +++ b/Lib/test/test_ctypes/test_slicing.py @@ -63,6 +63,35 @@ def test_setslice_cint(self): with self.assertRaises(ValueError): a[:5] = range(32) + def test_setslice_len_error(self): + # gh-161840: exceptions from PySequence_Length() must propagate + # instead of being replaced with ValueError. + class CustomError(Exception): + pass + + class BadLen: + def __len__(self): + raise CustomError("boom") + + class BadValueErrorLen: + def __len__(self): + raise ValueError("custom value error") + + a = (c_int * 3)(1, 2, 3) + with self.assertRaisesRegex(CustomError, "boom"): + a[0:1] = BadLen() + with self.assertRaisesRegex(CustomError, "boom"): + a[0:0] = BadLen() + with self.assertRaisesRegex(CustomError, "boom"): + a[::2] = BadLen() + with self.assertRaisesRegex(ValueError, "custom value error"): + a[0:1] = BadValueErrorLen() + with self.assertRaisesRegex(TypeError, "object of type 'int' has no len"): + a[0:1] = 42 + with self.assertRaisesRegex(TypeError, "dict is not a sequence"): + a[0:1] = {"x": 1} + self.assertEqual(a[:], [1, 2, 3]) + def test_char_ptr(self): s = b"abcdefghijklmnopqrstuvwxyz" diff --git a/Misc/NEWS.d/next/Library/2026-11-12-08-38-09.gh-issue-161840.YcEVjO.rst b/Misc/NEWS.d/next/Library/2026-11-12-08-38-09.gh-issue-161840.YcEVjO.rst new file mode 100644 index 00000000000000..f1e63af06fef87 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-12-08-38-09.gh-issue-161840.YcEVjO.rst @@ -0,0 +1,3 @@ +Propagate exceptions raised while getting the length of the assigned value +in :mod:`ctypes` array slice assignment instead of replacing them with a +:exc:`ValueError`. diff --git a/Modules/_ctypes/_ctypes.c b/Modules/_ctypes/_ctypes.c index d0613a0260d4fd..8aed4a49bde373 100644 --- a/Modules/_ctypes/_ctypes.c +++ b/Modules/_ctypes/_ctypes.c @@ -5327,6 +5327,9 @@ Array_ass_subscript_lock_held(PyObject *myself, PyObject *item, PyObject *value) stop = start; otherlen = PySequence_Length(value); + if (otherlen < 0) { + return -1; + } if (otherlen != slicelen) { PyErr_SetString(PyExc_ValueError, "Can only assign sequence of same size");