diff --git a/Lib/test/test_array.py b/Lib/test/test_array.py index 580966589fdd6b..58e4b33df15689 100755 --- a/Lib/test/test_array.py +++ b/Lib/test/test_array.py @@ -105,6 +105,19 @@ def __index__(self): with self.assertRaises(TypeError): a.fromlist(lst) + @subTests("typecode", ["e", "f", "d", "Zf", "Zd"]) + def test_setitem_conversion_error(self, typecode): + class BadNumber: + def __float__(self): + raise ValueError("conversion failed") + + __complex__ = __float__ + + a = array.array(typecode, [-1, 42]) + with self.assertRaisesRegex(ValueError, "conversion failed"): + a[1] = BadNumber() + self.assertEqual(a.tolist(), [-1, 42]) + def test_typecodes(self): self.assertIsInstance(array.typecodes, tuple) for typecode in array.typecodes: diff --git a/Misc/NEWS.d/next/Library/2026-11-23-23-11-49.gh-issue-162507.hG5bdI.rst b/Misc/NEWS.d/next/Library/2026-11-23-23-11-49.gh-issue-162507.hG5bdI.rst new file mode 100644 index 00000000000000..e22f25d2aab915 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-23-23-11-49.gh-issue-162507.hG5bdI.rst @@ -0,0 +1,2 @@ +Speed up writes to floating-point and complex :class:`array.array` objects. +Patch by Maurycy Pawłowski-Wieroński. diff --git a/Modules/arraymodule.c b/Modules/arraymodule.c index 64dacd1b8f1f61..a484dba703c165 100644 --- a/Modules/arraymodule.c +++ b/Modules/arraymodule.c @@ -584,8 +584,8 @@ e_getitem(arrayobject *ap, Py_ssize_t i) static int e_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v) { - double x; - if (!PyArg_Parse(v, "d;array item must be float", &x)) { + double x = PyFloat_AsDouble(v); + if (x == -1.0 && PyErr_Occurred()) { return -1; } @@ -607,9 +607,10 @@ f_getitem(arrayobject *ap, Py_ssize_t i) static int f_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v) { - double x; - if (!PyArg_Parse(v, "d;array item must be float", &x)) + double x = PyFloat_AsDouble(v); + if (x == -1.0 && PyErr_Occurred()) { return -1; + } CHECK_ARRAY_BOUNDS(ap, i); @@ -629,9 +630,10 @@ d_getitem(arrayobject *ap, Py_ssize_t i) static int d_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v) { - double x; - if (!PyArg_Parse(v, "d;array item must be float", &x)) + double x = PyFloat_AsDouble(v); + if (x == -1.0 && PyErr_Occurred()) { return -1; + } CHECK_ARRAY_BOUNDS(ap, i); @@ -652,9 +654,8 @@ cf_getitem(arrayobject *ap, Py_ssize_t i) static int cf_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v) { - Py_complex x; - - if (!PyArg_Parse(v, "D;array item must be complex", &x)) { + Py_complex x = PyComplex_AsCComplex(v); + if (PyErr_Occurred()) { return -1; } @@ -688,10 +689,9 @@ cd_getitem(arrayobject *ap, Py_ssize_t i) static int cd_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v) { - Py_complex x; + Py_complex x = PyComplex_AsCComplex(v); double f[2]; - - if (!PyArg_Parse(v, "D;array item must be complex", &x)) { + if (PyErr_Occurred()) { return -1; }