From ce19aa4196cb4653c288983925e05a96ea0b7c37 Mon Sep 17 00:00:00 2001 From: ayushm98 Date: Mon, 29 Dec 2025 16:40:50 -0600 Subject: [PATCH] Fix queue.SimpleQueue.__sizeof__() to account for buffer Fixes #140025 The __sizeof__() method for queue.SimpleQueue previously ignored the underlying RingBuf data structure, only returning the basic object size. Now properly accounts for the dynamically allocated items array in the RingBuf, which grows with the queue capacity: - Returns base object size + (items_cap * sizeof(PyObject*)) This gives accurate memory usage for SimpleQueue instances. --- Modules/_queuemodule.c | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/Modules/_queuemodule.c b/Modules/_queuemodule.c index 01235c77bd7db8..2c1d305540065a 100644 --- a/Modules/_queuemodule.c +++ b/Modules/_queuemodule.c @@ -524,6 +524,15 @@ queue_free(void *m) (void)queue_clear((PyObject *)m); } +static PyObject * +simplequeue_sizeof(simplequeueobject *self, PyObject *Py_UNUSED(ignored)) +{ + Py_ssize_t res = _PyObject_SIZE(Py_TYPE(self)); + // Add size of the RingBuf items array + res += self->buf.items_cap * sizeof(PyObject *); + return PyLong_FromSsize_t(res); +} + #include "clinic/_queuemodule.c.h" @@ -534,6 +543,8 @@ static PyMethodDef simplequeue_methods[] = { _QUEUE_SIMPLEQUEUE_PUT_METHODDEF _QUEUE_SIMPLEQUEUE_PUT_NOWAIT_METHODDEF _QUEUE_SIMPLEQUEUE_QSIZE_METHODDEF + {"__sizeof__", (PyCFunction)simplequeue_sizeof, + METH_NOARGS, PyDoc_STR("Return the size of the SimpleQueue in memory, in bytes.")}, {"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS, PyDoc_STR("See PEP 585")}, {NULL, NULL} /* sentinel */