]> granicus.if.org Git - python/commitdiff
Correct one of the "MemoryError oddities":
authorAmaury Forgeot d'Arc <amauryfa@gmail.com>
Thu, 31 Jul 2008 22:56:02 +0000 (22:56 +0000)
committerAmaury Forgeot d'Arc <amauryfa@gmail.com>
Thu, 31 Jul 2008 22:56:02 +0000 (22:56 +0000)
the traceback would grow each time a MemoryError is raised.

Lib/test/test_exceptions.py
Python/errors.c

index 2b248e1fd3362015b4f93327b9259b11cb7acc57..b742fcefd735d267d71b0a0692384cbeeb7e22ce 100644 (file)
@@ -596,6 +596,24 @@ class ExceptionTests(unittest.TestCase):
                          "Exception ValueError: ValueError() "
                          "in <class 'KeyError'> ignored\n")
 
+
+    def test_MemoryError(self):
+        # PyErr_NoMemory always raises the same exception instance.
+        # Check that the traceback is not doubled.
+        import traceback
+        def raiseMemError():
+            try:
+                "a" * (sys.maxsize // 2)
+            except MemoryError as e:
+                tb = e.__traceback__
+            else:
+                self.fail("Should have raises a MemoryError")
+            return traceback.format_tb(tb)
+
+        tb1 = raiseMemError()
+        tb2 = raiseMemError()
+        self.assertEqual(tb1, tb2)
+
 def test_main():
     run_unittest(ExceptionTests)
 
index a06ec02d9ab06f8798b5f1342a5bf77e583a5709..5ee6255a2a042da0d96da1a7045cfd1d0d1f5b72 100644 (file)
@@ -321,7 +321,17 @@ PyErr_NoMemory(void)
 
        /* raise the pre-allocated instance if it still exists */
        if (PyExc_MemoryErrorInst)
+       {
+               /* Clear the previous traceback, otherwise it will be appended
+                * to the current one.
+                *
+                * The following statement is not likely to raise any error;
+                * if it does, we simply discard it.
+                */
+               PyException_SetTraceback(PyExc_MemoryErrorInst, Py_None);
+
                PyErr_SetObject(PyExc_MemoryError, PyExc_MemoryErrorInst);
+       }
        else
                /* this will probably fail since there's no memory and hee,
                   hee, we have to instantiate this class