From 9d82a670f136b669d318581903469640a4be6fe2 Mon Sep 17 00:00:00 2001 From: DexFinder <63297382+shuimu5418@users.noreply.github.com> Date: Wed, 11 Jun 2025 21:12:47 +0800 Subject: [PATCH 1/2] gh-135385: Fix memory regression for classes with both __slots__ and __dict__ --- .../2025-06-11-21-40-21.gh-issue-135385.e2TFON.rst | 2 ++ Objects/typeobject.c | 14 +++++++++++++- 2 files changed, 15 insertions(+), 1 deletion(-) create mode 100644 Misc/NEWS.d/next/Core_and_Builtins/2025-06-11-21-40-21.gh-issue-135385.e2TFON.rst diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2025-06-11-21-40-21.gh-issue-135385.e2TFON.rst b/Misc/NEWS.d/next/Core_and_Builtins/2025-06-11-21-40-21.gh-issue-135385.e2TFON.rst new file mode 100644 index 00000000000000..50cbe8f9091432 --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2025-06-11-21-40-21.gh-issue-135385.e2TFON.rst @@ -0,0 +1,2 @@ +Fixed a memory regression for classes that have both ``__slots__`` and +``__dict__``. diff --git a/Objects/typeobject.c b/Objects/typeobject.c index db923c164774b7..1e974669ba20a7 100644 --- a/Objects/typeobject.c +++ b/Objects/typeobject.c @@ -4621,7 +4621,19 @@ type_new_descriptors(const type_new_ctx *ctx, PyTypeObject *type) } type->tp_basicsize = slotoffset; - type->tp_itemsize = ctx->base->tp_itemsize; + + // Only inherit tp_itemsize if this type defines its own __slots__ + // Classes that don't define __slots__ but inherit from __slots__ classes + // should not inherit tp_itemsize as they don't use variable-size items + if (et->ht_slots != NULL && PyTuple_GET_SIZE(et->ht_slots) > 0) { + // This type defines its own __slots__, inherit tp_itemsize + type->tp_itemsize = ctx->base->tp_itemsize; + } + else { + // This type doesn't define __slots__, don't inherit tp_itemsize + type->tp_itemsize = 0; + } + type->tp_members = _PyHeapType_GET_MEMBERS(et); return 0; } From 7ed3c02bb48fa2274f4c8903f3f853dda396997c Mon Sep 17 00:00:00 2001 From: BinFinder <63297382+shuimu5418@users.noreply.github.com> Date: Thu, 12 Jun 2025 00:21:47 +0800 Subject: [PATCH 2/2] Update Misc/NEWS.d/next/Core_and_Builtins/2025-06-11-21-40-21.gh-issue-135385.e2TFON.rst Co-authored-by: Peter Bierma --- .../2025-06-11-21-40-21.gh-issue-135385.e2TFON.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2025-06-11-21-40-21.gh-issue-135385.e2TFON.rst b/Misc/NEWS.d/next/Core_and_Builtins/2025-06-11-21-40-21.gh-issue-135385.e2TFON.rst index 50cbe8f9091432..99824404dfd7f4 100644 --- a/Misc/NEWS.d/next/Core_and_Builtins/2025-06-11-21-40-21.gh-issue-135385.e2TFON.rst +++ b/Misc/NEWS.d/next/Core_and_Builtins/2025-06-11-21-40-21.gh-issue-135385.e2TFON.rst @@ -1,2 +1,2 @@ -Fixed a memory regression for classes that have both ``__slots__`` and -``__dict__``. +Fix a memory regression for classes that have both :attr:`~object.__slots__` and +:attr:`~object.__dict__`.