Make error_already_set fetch and hold the Python error

This clears the Python error at the error_already_set throw site, thus
allowing Python calls to be made in destructors which are triggered by
the exception. This is preferable to the alternative, which would be
guarding every Python API call with an error_scope.

This effectively flips the behavior of error_already_set. Previously,
it was assumed that the error stays in Python, so handling the exception
in C++ would require explicitly calling PyErr_Clear(), but nothing was
needed to propagate the error to Python. With this change, handling the
error in C++ does not require a PyErr_Clear() call, but propagating the
error to Python requires an explicit error_already_set::restore().

The change does not break old code which explicitly calls PyErr_Clear()
for cleanup, which should be the majority of user code. The need for an
explicit restore() call does break old code, but this should be mostly
confined to the library and not user code.
This commit is contained in:
Dean Moldovan
2016-09-10 11:58:02 +02:00
parent 720136bfa7
commit 135ba8deaf
7 changed files with 44 additions and 6 deletions

View File

@@ -66,6 +66,13 @@ void throws_logic_error() {
throw std::logic_error("this error should fall through to the standard handler");
}
struct PythonCallInDestructor {
PythonCallInDestructor(const py::dict &d) : d(d) {}
~PythonCallInDestructor() { d["good"] = py::cast(true); }
py::dict d;
};
test_initializer custom_exceptions([](py::module &m) {
// make a new custom exception and use it as a translation target
static py::exception<MyException> ex(m, "MyException");
@@ -123,4 +130,15 @@ test_initializer custom_exceptions([](py::module &m) {
PyErr_SetString(PyExc_ValueError, "foo");
throw py::error_already_set();
});
m.def("python_call_in_destructor", [](py::dict d) {
try {
PythonCallInDestructor set_dict_in_destructor(d);
PyErr_SetString(PyExc_ValueError, "foo");
throw py::error_already_set();
} catch (const py::error_already_set&) {
return true;
}
return false;
});
});