Skip to content

Improve the error reporting for inc_ref GIL failures #4427

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

Merged
merged 5 commits into from
Dec 30, 2022
Merged
Changes from 1 commit
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
20 changes: 18 additions & 2 deletions include/pybind11/pytypes.h
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,7 @@ class handle : public detail::object_api<handle> {
#endif
#if defined(PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF)
if (m_ptr != nullptr && !PyGILState_Check()) {
throw std::runtime_error("pybind11::handle::inc_ref() PyGILState_Check() failure.");
throw_gilstate_error("pybind11::handle::inc_ref()");
}
#endif
Py_XINCREF(m_ptr);
Expand All @@ -267,7 +267,7 @@ class handle : public detail::object_api<handle> {
const handle &dec_ref() const & {
#if defined(PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF)
if (m_ptr != nullptr && !PyGILState_Check()) {
throw std::runtime_error("pybind11::handle::dec_ref() PyGILState_Check() failure.");
throw_gilstate_error("pybind11::handle::dec_ref()");
}
#endif
Py_XDECREF(m_ptr);
Expand Down Expand Up @@ -298,6 +298,22 @@ class handle : public detail::object_api<handle> {

#ifdef PYBIND11_HANDLE_REF_DEBUG
private:
void throw_gilstate_error(const std::string &function_name) const {
fprintf(stderr,
"%s is being called while PyGILState_Check() is failing. "
"This usually indicates that you are calling pybind11 functions without holding "
"the GIL or before "
"Python (and/or this Python module) is finished initializing.\n",
function_name.c_str());
if (Py_TYPE(m_ptr)->tp_name != nullptr) {
fprintf(stderr,
"The failing %s call was triggered on a %s object.\n",
function_name.c_str(),
Py_TYPE(m_ptr)->tp_name);
}
throw std::runtime_error(function_name + " PyGILState_Check() failure.");
}

static std::size_t inc_ref_counter(std::size_t add) {
thread_local std::size_t counter = 0;
counter += add;
Expand Down