closes bpo-31608: Fix a crash in methods of a subclass of _collections.deque with a bad __new__(). (GH-3788)

(cherry picked from commit 24bd50bdcc97d65130c07d6cd26085fd06c3e972)

Co-authored-by: Oren Milman <orenmn@gmail.com>
diff --git a/Lib/test/test_deque.py b/Lib/test/test_deque.py
index e895c3c..9211360 100644
--- a/Lib/test/test_deque.py
+++ b/Lib/test/test_deque.py
@@ -892,6 +892,21 @@
         d1 == d2   # not clear if this is supposed to be True or False,
                    # but it used to give a SystemError
 
+    @support.cpython_only
+    def test_bug_31608(self):
+        # The interpreter used to crash in specific cases where a deque
+        # subclass returned a non-deque.
+        class X(deque):
+            pass
+        d = X()
+        def bad___new__(cls, *args, **kwargs):
+            return [42]
+        X.__new__ = bad___new__
+        with self.assertRaises(TypeError):
+            d * 42  # shouldn't crash
+        with self.assertRaises(TypeError):
+            d + deque([1, 2, 3])  # shouldn't crash
+
 
 class SubclassWithKwargs(deque):
     def __init__(self, newarg=1):