New submission from STINNER Victor <vstin...@python.org>:

In C, the following pattern (A) is very common:

    Py_INCREF(sysdict);
    interp->sysdict = sysdict;

* (1) Increment the reference counter
* (2) Store a reference to the object somewhere

Similar pattern (B) using return:

    Py_INCREF(temp);
    return temp;

The problem in these patterns is that the object has to be written twice. I 
propose to add a simple new Py_NewRef() function which returns a new strong 
reference. In short, it's just:

static inline PyObject* Py_NewRef(PyObject *obj)
{
    Py_INCREF(obj);
    return obj;
}

(The actual implementation is just a little bit more complex, to also export it 
as a regular function.)

Pattern (A) becomes:

    interp->sysdict = Py_NewRef(sysdict);

Pattern (B) becomes:

    
    return Py_NewRef(temp);

Py_NewRef() might help to prepare a C extension to be converted to HPy which 
uses a HPy_Dup() function. HPy_Dup() is different than "Py_INCREF(obj), obj" 
for subtle reasons. I let you dig into HPy documentation for the rationale:

https://hpy.readthedocs.io/en/latest/api.html#handles

Even if you ignore HPy, Py_NewRef() avoids to repeat the object variable, and 
so makes the code simpler. Simple example:

-#define Py_RETURN_NONE return Py_INCREF(Py_None), Py_None
+#define Py_RETURN_NONE return Py_NewRef(Py_None)

----------
components: C API
messages: 380337
nosy: vstinner
priority: normal
severity: normal
status: open
title: [C API] Add Py_NewRef() function to get a new strong reference to an 
object
versions: Python 3.10

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue42262>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to