Skip to content

Commit c37aaff

Browse files
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 <noreply@anthropic.com>
1 parent ebd4a5d commit c37aaff

3 files changed

Lines changed: 27 additions & 0 deletions

File tree

‎Lib/test/test_descr.py‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2447,6 +2447,27 @@ class Weak(object):
24472447
self.assertEqual(r(), None)
24482448
del r
24492449

2450+
def test_weakrefs_from_secondary_base(self):
2451+
# gh-95710: weak references are supported if any base supports them,
2452+
# even if the primary base is a variable-size type.
2453+
import weakref
2454+
class Weak:
2455+
pass
2456+
for base, arg in (int, 42), (tuple, (1, 2)), (bytes, b'ab'):
2457+
with self.subTest(base=base):
2458+
class C(base, Weak):
2459+
pass
2460+
c = C(arg)
2461+
r = weakref.ref(c)
2462+
self.assertIs(r(), c)
2463+
self.assertEqual(c, arg)
2464+
del c
2465+
support.gc_collect()
2466+
self.assertIsNone(r())
2467+
class D(base):
2468+
pass
2469+
self.assertRaises(TypeError, weakref.ref, D(arg))
2470+
24502471
def test_properties(self):
24512472
# Testing property...
24522473
class C(object):
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Instances of a class that inherits from a variable-size built-in type
2+
(such as :class:`int` or :class:`tuple`)
3+
and from a class supporting weak references
4+
now support weak references too.

‎Objects/typeobject.c‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4357,6 +4357,8 @@ type_new_slots(type_new_ctx *ctx, PyObject *dict)
43574357
if (ctx->may_add_weak && ctx->base->tp_itemsize == 0) {
43584358
ctx->add_weak++;
43594359
}
4360+
/* Secondary bases may provide weakrefs */
4361+
type_new_slots_bases(ctx);
43604362
}
43614363
else {
43624364
/* Have slots */

0 commit comments

Comments
 (0)