Skip to content

ctor of object wrapper should propagate possible python exceptions #2195

Description

@MichaelSuen-thePointer

Issue description

In the ctor of every pybind object wrapper, if PyXXX_New returns nullptr, pybind will invoke pybind11_fail which throws std::runtime_error, which doesn't propagate the already set python MemoryError

pybind should throw a std::bad_alloc or at least py::error_already_set if it detects a python exception is set

py::tuple as a example

Some other places in the code also not propagating MemoryError, like pybind11.hpp#340

Reproducible example code

#include<pybind11/pybind11.h>namespacepy= pybind11;
inline py::tuple make_huge_tuple_pybind() {
returnpy::tuple(2147483647);
}
inline py::object make_huge_tuple_cpy() {
auto tup = PyTuple_New(2147483647);
if (!tup) {
throwpy::error_already_set();
}
return py::reinterpret_steal<py::object>(tup);
}
PYBIND11_PLUGIN(pybindtest) {
py::modulem("pybindtest", "pybindtest");
m.def("make_huge_tuple_pybind", make_huge_tuple_pybind);
m.def("make_huge_tuple_cpy", make_huge_tuple_cpy);
return m.ptr();
}

calling make_huge_tuple_pybind in python got RuntimeError

calling make_buge_tuple_cpy in python got MemoryError

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions