@@ -250,9 +250,9 @@ class handle : public detail::object_api<handle> {
250
250
#ifdef PYBIND11_HANDLE_REF_DEBUG
251
251
inc_ref_counter (1 );
252
252
#endif
253
- #if defined( PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF)
253
+ #ifdef PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF
254
254
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()" );
256
256
}
257
257
#endif
258
258
Py_XINCREF (m_ptr);
@@ -265,9 +265,9 @@ class handle : public detail::object_api<handle> {
265
265
this function automatically. Returns a reference to itself.
266
266
\endrst */
267
267
const handle &dec_ref () const & {
268
- #if defined( PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF)
268
+ #ifdef PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF
269
269
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()" );
271
271
}
272
272
#endif
273
273
Py_XDECREF (m_ptr);
@@ -296,8 +296,28 @@ class handle : public detail::object_api<handle> {
296
296
protected:
297
297
PyObject *m_ptr = nullptr ;
298
298
299
- #ifdef PYBIND11_HANDLE_REF_DEBUG
300
299
private:
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
301
321
static std::size_t inc_ref_counter (std::size_t add) {
302
322
thread_local std::size_t counter = 0 ;
303
323
counter += add;
0 commit comments