Skip to content

ctor of object wrapper should propagate possible python exceptions #2195

@MichaelSuen-thePointer

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>

namespace py = pybind11;

inline py::tuple make_huge_tuple_pybind() {
    return py::tuple(2147483647);
}

inline py::object make_huge_tuple_cpy() {
    auto tup = PyTuple_New(2147483647);
    if (!tup) {
        throw py::error_already_set();
    }
    return py::reinterpret_steal<py::object>(tup);
}

PYBIND11_PLUGIN(pybindtest) {
    py::module m("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

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