Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 8cd990b

Browse files
committed
Add Py_NewRef() and Py_XNewRef() functions
1 parent 98a9dd9 commit 8cd990b

3 files changed

Lines changed: 31 additions & 0 deletions

File tree

README.rst

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,14 @@ Copy the header file in your project and include it using::
3131
Functions
3232
=========
3333

34+
Python 3.10
35+
-----------
36+
37+
::
38+
39+
PyObject* Py_NewRef(PyObject *obj);
40+
PyObject* Py_XNewRef(PyObject *obj);
41+
3442
Python 3.9
3543
----------
3644

pythoncapi_compat.h

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,18 @@ extern "C" {
1515
#include <Python.h>
1616
#include "frameobject.h" // PyFrameObject
1717

18+
// bpo-42262 added Py_NewRef() and Py_XNewRef()
19+
static inline PyObject* Py_NewRef(PyObject *obj)
20+
{
21+
Py_INCREF(obj);
22+
return obj;
23+
}
24+
25+
static inline PyObject* Py_XNewRef(PyObject *obj)
26+
{
27+
Py_XINCREF(obj);
28+
return obj;
29+
}
1830

1931
// bpo-39573: Py_TYPE(), Py_REFCNT() and Py_SIZE() can no longer be used
2032
// as l-value in Python 3.10.

tests/test_pythoncapi_compat.c

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,17 @@ test_object(PyObject *self, PyObject *ignored)
1818
return NULL;
1919
}
2020

21+
// Py_NewRef() and Py_XNewRef()
22+
Py_ssize_t refcnt = Py_REFCNT(obj);
23+
PyObject *obj2 = Py_NewRef(obj);
24+
assert(Py_REFCNT(obj) == (refcnt + 1));
25+
PyObject *obj3 = Py_XNewRef(obj);
26+
assert(Py_REFCNT(obj) == (refcnt + 2));
27+
assert(Py_XNewRef(NULL) == NULL);
28+
Py_DECREF(obj2);
29+
Py_DECREF(obj3);
30+
assert(Py_REFCNT(obj) == refcnt);
31+
2132
// test Py_SET_REFCNT
2233
Py_SET_REFCNT(obj, Py_REFCNT(obj));
2334
// test Py_SET_TYPE

0 commit comments

Comments
 (0)