Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable "factory sets error and returns nullptr" #4846

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions include/pybind11/detail/init.h
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ PYBIND11_NAMESPACE_BEGIN(initimpl)

inline void no_nullptr(void *ptr) {
if (!ptr) {
if (PyErr_Occurred()) {
throw error_already_set();
}
throw type_error("pybind11::init(): factory function returned nullptr");
}
}
Expand Down
10 changes: 10 additions & 0 deletions tests/test_factory_constructors.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -412,6 +412,16 @@ TEST_SUBMODULE(factory_constructors, m) {
"__init__", [](NoisyAlloc &a, int i, const std::string &) { new (&a) NoisyAlloc(i); });
});

struct FactoryErrorAlreadySet {};
py::class_<FactoryErrorAlreadySet>(m, "FactoryErrorAlreadySet")
.def(py::init([](bool set_error) -> FactoryErrorAlreadySet * {
if (!set_error) {
return new FactoryErrorAlreadySet();
}
py::set_error(PyExc_ValueError, "factory sets error and returns nullptr");
return nullptr;
}));

// static_assert testing (the following def's should all fail with appropriate compilation
// errors):
#if 0
Expand Down
7 changes: 7 additions & 0 deletions tests/test_factory_constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -514,3 +514,10 @@ def __init__(self, bad):
str(excinfo.value)
== "__init__(self, ...) called with invalid or missing `self` argument"
)


def test_factory_error_already_set():
obj = m.FactoryErrorAlreadySet(False)
assert isinstance(obj, m.FactoryErrorAlreadySet)
with pytest.raises(ValueError, match="factory sets error and returns nullptr"):
m.FactoryErrorAlreadySet(True)
Loading