diff --git a/Lib/test/test_io.py b/Lib/test/test_io.py index 32e908da203..b5506b0ac49 100644 --- a/Lib/test/test_io.py +++ b/Lib/test/test_io.py @@ -1567,6 +1567,12 @@ def isatty(self): pair = self.tp(SelectableIsAtty(True), SelectableIsAtty(True)) self.assertTrue(pair.isatty()) + def test_weakref_clearing(self): + brw = self.tp(self.MockRawIO(), self.MockRawIO()) + ref = weakref.ref(brw) + brw = None + ref = None # Shouldn't segfault. + class CBufferedRWPairTest(BufferedRWPairTest): tp = io.BufferedRWPair diff --git a/Misc/NEWS b/Misc/NEWS index 6eb64f95399..e7476e5d2b2 100644 --- a/Misc/NEWS +++ b/Misc/NEWS @@ -16,6 +16,9 @@ Core and Builtins Library ------- +- Issue #22517: When a io.BufferedRWPair object is deallocated, clear its + weakrefs. + - Issue #22448: Improve canceled timer handles cleanup to prevent unbound memory usage. Patch by Joshua Moore-Oliva. diff --git a/Modules/_io/bufferedio.c b/Modules/_io/bufferedio.c index 4c0262e25a2..302db0ae135 100644 --- a/Modules/_io/bufferedio.c +++ b/Modules/_io/bufferedio.c @@ -2297,6 +2297,8 @@ static void bufferedrwpair_dealloc(rwpair *self) { _PyObject_GC_UNTRACK(self); + if (self->weakreflist != NULL) + PyObject_ClearWeakRefs((PyObject *)self); Py_CLEAR(self->reader); Py_CLEAR(self->writer); Py_CLEAR(self->dict);