From c37aaff90c8f1b2881a732c2bab7868ef91bf237 Mon Sep 17 00:00:00 2001 From: Serhiy Storchaka Date: Sat, 28 Nov 2026 00:37:49 +0200 Subject: [PATCH] gh-95710: Support weak references for subclasses of variable-size types with a weakrefable secondary base Secondary bases are now checked for weak reference support also if __slots__ is not defined. Co-Authored-By: Claude Opus 5.5 --- Lib/test/test_descr.py | 21 +++++++++++++++++++ ...-11-26-12-30-00.gh-issue-95710.WkRefMI.rst | 4 ++++ Objects/typeobject.c | 2 ++ 3 files changed, 27 insertions(+) create mode 100644 Misc/NEWS.d/next/Core_and_Builtins/2026-11-26-12-30-00.gh-issue-95710.WkRefMI.rst diff --git a/Lib/test/test_descr.py b/Lib/test/test_descr.py index 2f5953ba096d439..85372340d311872 100644 --- a/Lib/test/test_descr.py +++ b/Lib/test/test_descr.py @@ -2447,6 +2447,27 @@ class Weak(object): self.assertEqual(r(), None) del r + def test_weakrefs_from_secondary_base(self): + # gh-95710: weak references are supported if any base supports them, + # even if the primary base is a variable-size type. + import weakref + class Weak: + pass + for base, arg in (int, 42), (tuple, (1, 2)), (bytes, b'ab'): + with self.subTest(base=base): + class C(base, Weak): + pass + c = C(arg) + r = weakref.ref(c) + self.assertIs(r(), c) + self.assertEqual(c, arg) + del c + support.gc_collect() + self.assertIsNone(r()) + class D(base): + pass + self.assertRaises(TypeError, weakref.ref, D(arg)) + def test_properties(self): # Testing property... class C(object): diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-11-26-12-30-00.gh-issue-95710.WkRefMI.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-26-12-30-00.gh-issue-95710.WkRefMI.rst new file mode 100644 index 000000000000000..c5be54fc67f7347 --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-26-12-30-00.gh-issue-95710.WkRefMI.rst @@ -0,0 +1,4 @@ +Instances of a class that inherits from a variable-size built-in type +(such as :class:`int` or :class:`tuple`) +and from a class supporting weak references +now support weak references too. diff --git a/Objects/typeobject.c b/Objects/typeobject.c index a2690e8e6aa5bac..9bd88581e52c217 100644 --- a/Objects/typeobject.c +++ b/Objects/typeobject.c @@ -4357,6 +4357,8 @@ type_new_slots(type_new_ctx *ctx, PyObject *dict) if (ctx->may_add_weak && ctx->base->tp_itemsize == 0) { ctx->add_weak++; } + /* Secondary bases may provide weakrefs */ + type_new_slots_bases(ctx); } else { /* Have slots */