Skip to content

Commit d7aace7

Browse files
[3.14] gh-140530: fix a reference leak in an error path for raise exc from cause (GH-140908) (#141282)
gh-140530: fix a reference leak in an error path for `raise exc from cause` (GH-140908) Fix a reference leak in `raise E from T` when `T` is an exception subtype for which `T.__new__` does not return an exception instance. (cherry picked from commit 0c77e7c) Co-authored-by: Bénédikt Tran <[email protected]>
1 parent cb45871 commit d7aace7

File tree

3 files changed

+10
-11
lines changed

3 files changed

+10
-11
lines changed

Lib/test/test_raise.py

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -186,18 +186,14 @@ def test_class_cause(self):
186186
self.fail("No exception raised")
187187

188188
def test_class_cause_nonexception_result(self):
189-
class ConstructsNone(BaseException):
190-
@classmethod
189+
# See https://github.com/python/cpython/issues/140530.
190+
class ConstructMortal(BaseException):
191191
def __new__(*args, **kwargs):
192-
return None
193-
try:
194-
raise IndexError from ConstructsNone
195-
except TypeError as e:
196-
self.assertIn("should have returned an instance of BaseException", str(e))
197-
except IndexError:
198-
self.fail("Wrong kind of exception raised")
199-
else:
200-
self.fail("No exception raised")
192+
return ["mortal value"]
193+
194+
msg = ".*should have returned an instance of BaseException.*"
195+
with self.assertRaisesRegex(TypeError, msg):
196+
raise IndexError from ConstructMortal
201197

202198
def test_instance_cause(self):
203199
cause = KeyError()
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix a reference leak when ``raise exc from cause`` fails. Patch by Bénédikt
2+
Tran.

Python/ceval.c

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2108,6 +2108,7 @@ do_raise(PyThreadState *tstate, PyObject *exc, PyObject *cause)
21082108
"calling %R should have returned an instance of "
21092109
"BaseException, not %R",
21102110
cause, Py_TYPE(fixed_cause));
2111+
Py_DECREF(fixed_cause);
21112112
goto raise_error;
21122113
}
21132114
Py_DECREF(cause);

0 commit comments

Comments
 (0)