[binutils-gdb] [gdb/python] Introduce py_{none, true, false, notimplemented} functions

Tom de Vries via Gdb-cvs <[email protected]> Fri, 15 May 2026 19:38:19 +0000 (GMT)
Newsgroups gmane.comp.gdb.cvs
Message-ID <[email protected]>
https://sourceware.org/git/gitweb.cgi?p=binutils-gdb.git;h=b37f2bd246c3fb15e4e242ae5be95fc62a8858da

commit b37f2bd246c3fb15e4e242ae5be95fc62a8858da
Author: Tom de Vries <[email protected]>
Date:   Fri May 15 21:38:12 2026 +0200

    [gdb/python] Introduce py_{none,true,false,notimplemented} functions
    
    I came across this code:
    ...
       if (c)
         return v;
       else
         Py_RETURN_NONE;
    ...
    and realized I couldn't easily rewrite it into "return c ? v : ...".
    
    Probably something like this would work:
    ...
      return c ? v : ([] { Py_RETURN_NONE; } ());
    ...
    but it made me wonder if we can get rid of Py_RETURN_NONE.
    
    The only point of it seems to be to increase the reference count on the
    Py_None object for older python versions.
    
    Add a refcount-safe wrapper py_none (returning a gdbpy_ref), with the aim of
    replacing all uses of Py_RETURN_NONE with "return py_none ().release ()".
    
    Likewise for Py_RETURN_TRUE/Py_RETURN_FALSE/Py_RETURN_NOTIMPLEMENTED.
    
    Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=34145

Diff:
---
 gdb/python/python-internal.h | 31 +++++++++++++++++++++++++++++++
 1 file changed, 31 insertions(+)

diff --git a/gdb/python/python-internal.h b/gdb/python/python-internal.h
index 3147156d5be..5548c456af9 100644
--- a/gdb/python/python-internal.h
+++ b/gdb/python/python-internal.h
@@ -1343,4 +1343,35 @@ protected:
 extern int eval_python_command (const char *command, int start_symbol,
 				const char *filename = nullptr);
 
+/* The following four functions are refcount-safe wrappers around
+   Py_RETURN_{NONE,TRUE,FALSE,NOTIMPLEMENTED}.  */
+
+static inline gdbpy_ref<>
+py_none ()
+{
+  auto f = [] { Py_RETURN_NONE; };
+  return gdbpy_ref<> (f ());
+}
+
+static inline gdbpy_ref<>
+py_true ()
+{
+  auto f = [] { Py_RETURN_TRUE; };
+  return gdbpy_ref<> (f ());
+}
+
+static inline gdbpy_ref<>
+py_false ()
+{
+  auto f = [] { Py_RETURN_FALSE; };
+  return gdbpy_ref<> (f ());
+}
+
+static inline gdbpy_ref<>
+py_notimplemented ()
+{
+  auto f = [] { Py_RETURN_NOTIMPLEMENTED; };
+  return gdbpy_ref<> (f ());
+}
+
 #endif /* GDB_PYTHON_PYTHON_INTERNAL_H */