@@ -250,9 +250,9 @@ class handle : public detail::object_api<handle> {
250250#ifdef PYBIND11_HANDLE_REF_DEBUG
251251 inc_ref_counter (1 );
252252#endif
253- #if defined( PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF)
253+ #ifdef PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF
254254 if (m_ptr != nullptr && !PyGILState_Check ()) {
255- throw std::runtime_error (" pybind11::handle::inc_ref() PyGILState_Check() failure. " );
255+ throw_gilstate_error (" pybind11::handle::inc_ref()" );
256256 }
257257#endif
258258 Py_XINCREF (m_ptr);
@@ -265,9 +265,9 @@ class handle : public detail::object_api<handle> {
265265 this function automatically. Returns a reference to itself.
266266 \endrst */
267267 const handle &dec_ref () const & {
268- #if defined( PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF)
268+ #ifdef PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF
269269 if (m_ptr != nullptr && !PyGILState_Check ()) {
270- throw std::runtime_error (" pybind11::handle::dec_ref() PyGILState_Check() failure. " );
270+ throw_gilstate_error (" pybind11::handle::dec_ref()" );
271271 }
272272#endif
273273 Py_XDECREF (m_ptr);
@@ -296,8 +296,28 @@ class handle : public detail::object_api<handle> {
296296protected:
297297 PyObject *m_ptr = nullptr ;
298298
299- #ifdef PYBIND11_HANDLE_REF_DEBUG
300299private:
300+ #ifdef PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF
301+ void throw_gilstate_error (const std::string &function_name) const {
302+ fprintf (
303+ stderr,
304+ " %s is being called while the GIL is either not held or invalid. Please see "
305+ " https://pybind11.readthedocs.io/en/stable/advanced/"
306+ " misc.html#common-sources-of-global-interpreter-lock-errors for debugging advice.\n " ,
307+ function_name.c_str ());
308+ fflush (stderr);
309+ if (Py_TYPE (m_ptr)->tp_name != nullptr ) {
310+ fprintf (stderr,
311+ " The failing %s call was triggered on a %s object.\n " ,
312+ function_name.c_str (),
313+ Py_TYPE (m_ptr)->tp_name );
314+ fflush (stderr);
315+ }
316+ throw std::runtime_error (function_name + " PyGILState_Check() failure." );
317+ }
318+ #endif
319+
320+ #ifdef PYBIND11_HANDLE_REF_DEBUG
301321 static std::size_t inc_ref_counter (std::size_t add) {
302322 thread_local std::size_t counter = 0 ;
303323 counter += add;
0 commit comments