-
-
Notifications
You must be signed in to change notification settings - Fork 30.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
C API: Add PyTuple_GetItemRef(), similar to PyTuple_GetItem() but return a strong reference #117518
Comments
Replace Py_NewRef(PyTuple_GET_ITEM(tuple, pos)) with PyTuple_GetItemRef(tuple, pos).
Replace Py_NewRef(PyTuple_GET_ITEM(tuple, pos)) with PyTuple_GetItemRef(tuple, pos).
@colesbury @erlend-aasland @serhiy-storchaka: What do you think of adding this function? |
I'm not a part of the C API WG, but I'm +1 ;) |
I do not think it is needed. Adding it means that there is something wrong with Adding |
The problem is not the PyObject *tuple = Py_BuildValue("(iii)", 2000, 3000, 4000);
PyObject *number = PyTuple_GetItem(tuple, 0);
Py_DECREF(tuple);
// number is now a dangling pointer
... code using 'number' variable ... Correct code using only strong references: PyObject *tuple = Py_BuildValue("(iii)", 2000, 3000, 4000);
PyObject *number = PyTuple_GetItemRef(tuple, 0);
Py_DECREF(tuple);
// number is now a dangling pointer
... code using 'number' variable ...
Py_DECREF(number); My intent is to have a subset of the C API which does not use borrowed references, or at least, hide functions returning borrowed references, when alternativates using strong references exists. See also PEP 743 – Add Py_COMPAT_API_VERSION to the Python C API. |
I don't plan to deprecate PyTuple_GetItem(). You can still use it if you are sure that you are holding a strong reference to the container (the tuple) while using its items. |
I suggest opening an issue on the C API WG bug tracker. |
If you want to create a strong reference, just call |
After re-reading PEP-703 I'm +0. Quoting from the PEP:
|
See also this numpy issue: numpy/numpy#26159 |
That issue does not mention |
…doc (pythonGH-117920) (cherry picked from commit 4605a19) Co-authored-by: Victor Stinner <vstinner@python.org>
The documentation was completed to clarify that it returns a borrow reference. |
I propose to add a new PyTuple_GetItemRef() function, similar to PyTuple_GetItem() but return a strong reference instead of a borrowed reference.
Other functions were added recently to return a strong reference:
PyList_GetItemRef
, a variant ofPyList_GetItem
that returns a strong reference #114329I already proposed adding PyTuple_GetItemRef() in 2020, but the idea was rejected: issue gh-86460. Since 2020, Free Threading (PEP 703) was added to Python and borrowed references don't play well with Free Threading.
Linked PRs
The text was updated successfully, but these errors were encountered: