You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
sum() deallocates float subclass instances as exact floats in the complex fast path #150868
In builtin_sum_impl() (Python/bltinmodule.c), the complex-number fast
path tests items with PyFloat_Check() but releases them with _Py_DECREF_SPECIALIZED(item, _PyFloat_ExactDealloc).
PyFloat_Check() also matches subclasses of float, whereas _PyFloat_ExactDealloc is only valid for exact float objects. When a float subclass instance reaches refcount 0 through this path, it is
deallocated as an exact float, bypassing its real tp_dealloc
(instance __dict__, weakref list, and GC bookkeeping). This can leak
memory and leave the cyclic GC in an inconsistent state.
The adjacent float fast path in the same function already guards the
identical specialized dealloc with PyFloat_CheckExact(); only the
complex branch uses the broader PyFloat_Check().
Reproducer
classF(float):
pass# complex start value selects the complex fast pathsum([F(1.0), F(2.0)], 0j)
Proposed fix
In the complex branch, use PyFloat_CheckExact(item) instead of PyFloat_Check(item), so subclass instances fall through to the generic PyNumber_Add path with a normal Py_DECREF. Numeric behavior is
unchanged.
Environment
CPython: main branch (please confirm the line is still present)
FWIW: I benchmarked the _Py_DECREF_SPECIALIZED and on PGO builds there is hardly any performance difference with the normal Py_DECREF. So for any PR that makes not a big difference.
Activity
skirpichev commentedon Jun 4, 2026
Thanks for the fix, that's my fault. That was noticed before, but not fixed, unfortunately.
Though, note that in some branches - subclasses are handled. I think we should apply also
CC @rhettinger
eendebakpt commentedon Jun 7, 2026
FWIW: I benchmarked the
_Py_DECREF_SPECIALIZEDand on PGO builds there is hardly any performance difference with the normalPy_DECREF. So for any PR that makes not a big difference.pythongh-150868: Also use exact-type checks for ints in the fast sum(…