24 #ifndef LSST_PEX_EXCEPTIONS_PYTHON_EXCEPTION_H
25 #define LSST_PEX_EXCEPTIONS_PYTHON_EXCEPTION_H
29 #include <pybind11/pybind11.h>
35 namespace exceptions {
46 template <
typename T,
typename E=lsst::pex::exceptions::Exception>
47 pybind11::class_<T>
declareException(pybind11::module &mod,
const std::string & name,
const std::string & base) {
48 namespace py = pybind11;
55 py::class_<T, E> cls(mod, name.c_str());
60 auto exceptions = py::reinterpret_steal<py::object>(PyImport_ImportModule(
"lsst.pex.exceptions.wrappers"));
61 if (!exceptions.ptr()) {
62 PyErr_SetString(PyExc_SystemError,
"import failed");
63 throw py::error_already_set();
66 auto declare = py::reinterpret_steal<py::object>(PyObject_GetAttrString(exceptions.ptr(),
"declare"));
68 PyErr_SetString(PyExc_SystemError,
"could not get declare function from Python");
69 throw py::error_already_set();
72 auto baseCls = py::reinterpret_steal<py::object>(PyObject_GetAttrString(exceptions.ptr(), base.c_str()));
74 PyErr_SetString(PyExc_SystemError,
"could not get base class");
75 throw py::error_already_set();
78 auto exceptionName = py::reinterpret_steal<py::object>(PYBIND11_FROM_STRING(name.c_str()));
79 if (!exceptionName.ptr()) {
80 PyErr_SetString(PyExc_SystemError,
"could not create name string");
81 throw py::error_already_set();
84 auto result = py::reinterpret_steal<py::object>(PyObject_CallFunctionObjArgs(
declare.ptr(), mod.ptr(),
85 exceptionName.ptr(), baseCls.ptr(), cls.ptr(), NULL));
87 PyErr_SetString(PyExc_SystemError,
"could not declare exception");
88 throw py::error_already_set();
pybind11::class_< T > declareException(pybind11::module &mod, const std::string &name, const std::string &base)
Helper function for pybind11, used to define new types of exceptions.