merge 3.4 (#22517)
diff --git a/Lib/test/test_io.py b/Lib/test/test_io.py
index e499ba2..a3567fa 100644
--- a/Lib/test/test_io.py
+++ b/Lib/test/test_io.py
@@ -1628,6 +1628,12 @@
         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 4cb4601..774b9fa 100644
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -35,6 +35,9 @@
 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 2feda5a..3f14a20 100644
--- a/Modules/_io/bufferedio.c
+++ b/Modules/_io/bufferedio.c
@@ -2343,6 +2343,8 @@
 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);