Avoid throwing exception in ClosingTHPObjectPtr (#109758)

Previously, if ClosingTHPObjectPtr was destructed because we
were unwinding the stack from an exception, we would attempt to call
close() which just isn't going to work.  Two fixes:

1. Detect if we're unwinding due to a Python error, and don't try
   to do more Python stuff if so.

2. If close() fails somehow, write an unraisable exception, don't
   try to throw because that will terminate if you're in an
   exception.

Signed-off-by: Edward Z. Yang <ezyang@meta.com>

Pull Request resolved: https://github.com/pytorch/pytorch/pull/109758
Approved by: https://github.com/jansel
This commit is contained in:
Edward Z. Yang
2023-09-20 20:29:54 -04:00
committed by PyTorch MergeBot
parent 2cd0b94533
commit 0351e2042b

View File

@ -290,8 +290,15 @@ static PyObject* call_end_capture(PyObject* self, const variable_list& inputs) {
struct ClosingTHPObjectPtr : public THPObjectPtr {
ClosingTHPObjectPtr(PyObject* o) : THPObjectPtr(o) {}
~ClosingTHPObjectPtr() {
if (PyErr_Occurred()) {
// do nothing, do not attempt to close
return;
}
static PyObject* method_name = PyUnicode_InternFromString("close");
check(PyObject_CallMethodNoArgs(get(), method_name));
if (PyObject_CallMethodNoArgs(get(), method_name) == nullptr) {
PyErr_WriteUnraisable(get());
PyErr_Clear();
}
}
};