Skip to content

Commit 9cbbb47

Browse files
Include inline values in sys.getsizeof
1 parent 5e65a1a commit 9cbbb47

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed

Lib/test/test_sys.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,10 @@ def requires_subinterpreters(meth):
3131
return unittest.skipIf(interpreters is None,
3232
'subinterpreters required')(meth)
3333

34+
class ObjectWithValue:
35+
value: ObjectWithValue | None
36+
def __init__(self, value):
37+
self.value = value
3438

3539
DICT_KEY_STRUCT_FORMAT = 'n2BI2n'
3640

@@ -1475,6 +1479,16 @@ def test_gc_head_size(self):
14751479
# but lists are
14761480
self.assertEqual(sys.getsizeof([]), vsize('Pn') + gc_header_size)
14771481

1482+
def test_inline_values(self):
1483+
vsize = test.support.calcvobjsize
1484+
gc_header_size = self.gc_headsize
1485+
inline_values_size = 32
1486+
1487+
linked_list = None
1488+
for i in range(28):
1489+
linked_list = ObjectWithValue(linked_list)
1490+
self.assertEqual(sys.getsizeof(linked_list), vsize('P') + gc_header_size + inline_values_size)
1491+
14781492
def test_errors(self):
14791493
class BadSizeof:
14801494
def __sizeof__(self):

Python/sysmodule.c

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1842,10 +1842,11 @@ _PySys_GetSizeOf(PyObject *o)
18421842
PyObject *res = NULL;
18431843
PyObject *method;
18441844
Py_ssize_t size;
1845+
PyTypeObject *type = Py_TYPE(o);
18451846
PyThreadState *tstate = _PyThreadState_GET();
18461847

18471848
/* Make sure the type is initialized. float gets initialized late */
1848-
if (PyType_Ready(Py_TYPE(o)) < 0) {
1849+
if (PyType_Ready(type) < 0) {
18491850
return (size_t)-1;
18501851
}
18511852

@@ -1854,7 +1855,7 @@ _PySys_GetSizeOf(PyObject *o)
18541855
if (!_PyErr_Occurred(tstate)) {
18551856
_PyErr_Format(tstate, PyExc_TypeError,
18561857
"Type %.100s doesn't define __sizeof__",
1857-
Py_TYPE(o)->tp_name);
1858+
type->tp_name);
18581859
}
18591860
}
18601861
else {
@@ -1876,6 +1877,10 @@ _PySys_GetSizeOf(PyObject *o)
18761877
return (size_t)-1;
18771878
}
18781879

1880+
if (type->tp_flags & Py_TPFLAGS_INLINE_VALUES) {
1881+
size += _PyInlineValuesSize(type);
1882+
}
1883+
18791884
size_t presize = 0;
18801885
if (!Py_IS_TYPE(o, &PyType_Type) ||
18811886
PyType_HasFeature((PyTypeObject *)o, Py_TPFLAGS_HEAPTYPE))

0 commit comments

Comments
 (0)