cpython icon indicating copy to clipboard operation
cpython copied to clipboard

Replace Py_INCREF()/Py_XINCREF() usage with Py_NewRef()/Py_XNewRef()

Open vstinner opened this issue 1 year ago • 0 comments

I added Py_NewRef() and Py_XNewRef() to Python 3.10 C API. IMO using them make to code easier to read and make the code looks "more correct". Examples:

(A) Assign + INCREF:

-                result = Py_False;
-                Py_INCREF(result);
+                result = Py_NewRef(Py_False);

(B) INCREF + assign:

-        Py_INCREF(last);
-        self->last = last;
+        self->last = Py_NewRef(last);

(C) INCREF + return:

-    Py_XINCREF(result);
-    return result;
+    return Py_XNewRef(result);

While technically, Py_INCREF() and Py_XINCREF() modify the object in-place (increment their reference counter), for me Py_NewRef() makes me sense: it creates "a new reference".

The example (A) is weird: it assigns a variable to something, and only later creates a new reference. For me, the syntax with Py_NewRef() makes more sense.

Examples (B) and (C) are shorter with Py_NewRef(), and again, IMO makes more sense and are more readable.

  • PR: gh-99302
  • PR: gh-99317
  • PR: gh-99318
  • PR: gh-99330
  • PR: gh-99332
  • PR: gh-99333
  • PR: gh-99335
  • PR: gh-99336
  • PR: gh-99351
  • PR: gh-99354

vstinner avatar Nov 09 '22 21:11 vstinner