tensorflow::MaybeRaiseFromStatus now raises builtin exception types

This allows to drop a dependency on py_exception_registry which brings
in a lot of other transitive dependencies.

Note also that it is no longer defined in tensorflow::pybind11 to
avoid conflict with PYBIND11_MODULE which does not refer to the
root pybind11 namespace (i.e. does pybind11:: instead of ::pybind11::)

PiperOrigin-RevId: 269544908
This commit is contained in:
Sergei Lebedev 2019-09-17 05:11:21 -07:00 committed by TensorFlower Gardener
parent 669841639f
commit 6a6e9bdaea
2 changed files with 28 additions and 19 deletions

View File

@ -384,8 +384,8 @@ cc_library(
hdrs = ["lib/core/pybind11_status.h"],
features = ["-parse_headers"],
deps = [
":py_exception_registry",
"//tensorflow/core:lib",
"//tensorflow/core:lib_internal",
"//tensorflow/core:protos_all_cc",
"//third_party/python_runtime:headers",
"@pybind11",
],

View File

@ -19,27 +19,36 @@ limitations under the License.
#include <Python.h>
#include "pybind11/pybind11.h"
#include "tensorflow/core/lib/core/error_codes.pb.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/python/lib/core/py_exception_registry.h"
namespace tensorflow {
namespace py = ::pybind11;
namespace internal {
namespace pybind11 {
inline void MaybeRaiseFromStatus(const Status& status) {
if (!status.ok()) {
// TODO(slebedev): translate to builtin exception classes instead?
auto* exc_type = PyExceptionRegistry::Lookup(status.code());
PyErr_SetObject(
exc_type,
py::make_tuple(nullptr, nullptr, status.error_message()).ptr());
throw py::error_already_set();
PyObject* StatusToPyExc(const Status& status) {
switch (status.code()) {
case error::Code::INVALID_ARGUMENT:
return PyExc_ValueError;
case error::Code::OUT_OF_RANGE:
return PyExc_IndexError;
case error::Code::UNIMPLEMENTED:
return PyExc_NotImplementedError;
default:
return PyExc_RuntimeError;
}
}
} // namespace internal
inline void MaybeRaiseFromStatus(const Status& status) {
if (!status.ok()) {
PyErr_SetString(internal::StatusToPyExc(status),
status.error_message().c_str());
throw pybind11::error_already_set();
}
}
} // namespace pybind11
} // namespace tensorflow
namespace pybind11 {
@ -51,11 +60,11 @@ namespace detail {
// by PyExceptionRegistry. Note that the registry should be initialized
// in order to be used, see PyExceptionRegistry::Init.
template <>
struct type_caster<::tensorflow::Status> {
struct type_caster<tensorflow::Status> {
public:
PYBIND11_TYPE_CASTER(::tensorflow::Status, _("Status"));
static handle cast(::tensorflow::Status status, return_value_policy, handle) {
tensorflow::pybind11::MaybeRaiseFromStatus(status);
PYBIND11_TYPE_CASTER(tensorflow::Status, _("Status"));
static handle cast(tensorflow::Status status, return_value_policy, handle) {
tensorflow::MaybeRaiseFromStatus(status);
return none();
}
};