From e3f9b944e0b60d119ec0a18aa5eb830c68b0dc3d Mon Sep 17 00:00:00 2001 From: opale-c Date: Wed, 3 Jun 2026 17:53:16 +0200 Subject: [PATCH] Update bltinmodule.c Fix incorrect specialized deallocation of float subclasses in sum() In the complex-number fast path of builtin_sum_impl ( Python/bltinmodule.c ), items are tested with PyFloat_Check() but then released with _Py_DECREF_SPECIALIZED(item, _PyFloat_ExactDealloc) . PyFloat_Check() also matches float subclasses, whereas _PyFloat_ExactDealloc is only valid for exact float objects. As a result, when summing instances of a float subclass into a complex start value, the subclass instances are deallocated as exact floats, bypassing their real tp_dealloc (instance __dict__ , weakref, and GC cleanup). This can leak memory and leave the GC in an inconsistent state. The adjacent float fast path already guards the same specialized dealloc with PyFloat_CheckExact() ; this change brings the complex path in line by using PyFloat_CheckExact() as well. Subclass instances then fall through to the generic PyNumber_Add path with a normal Py_DECREF , preserving numeric behavior while fixing the deallocation. Reproducer: class F(float): pass sum([F(1.0), F(2.0)], 0j) # subclass instances were freed as exact floats Change: in the complex branch of builtin_sum_impl , replace PyFloat_Check(item) with PyFloat_CheckExact(item) (one line). --- Python/bltinmodule.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/bltinmodule.c b/Python/bltinmodule.c index d5129bf6a5a6bc0..fbdd637a3fcb78d 100644 --- a/Python/bltinmodule.c +++ b/Python/bltinmodule.c @@ -3046,7 +3046,7 @@ builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start) return NULL; } } - if (PyFloat_Check(item)) { + if (PyFloat_CheckExact(item)) { double value = PyFloat_AS_DOUBLE(item); re_sum = cs_add(re_sum, value); _Py_DECREF_SPECIALIZED(item, _PyFloat_ExactDealloc);