Skip to content

Commit 0c77e7c

Browse files
authored
gh-140530: fix a reference leak in an error path for raise exc from cause (#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.
1 parent 5ba0a1a commit 0c77e7c

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
@@ -2148,6 +2148,7 @@ do_raise(PyThreadState *tstate, PyObject *exc, PyObject *cause)
21482148
"calling %R should have returned an instance of "
21492149
"BaseException, not %R",
21502150
cause, Py_TYPE(fixed_cause));
2151+
Py_DECREF(fixed_cause);
21512152
goto raise_error;
21522153
}
21532154
Py_DECREF(cause);

0 commit comments

Comments
 (0)