diff --git a/Lib/test/test_descr.py b/Lib/test/test_descr.py index 2f5953ba096d43..85372340d31187 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 00000000000000..c5be54fc67f734 --- /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 a2690e8e6aa5ba..9bd88581e52c21 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 */