Skip to content

gh-101233: Add part to explain Py_SETREF and Py_NewRef #101234

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions Doc/extending/newtypes_tutorial.rst
Original file line number Diff line number Diff line change
Expand Up @@ -425,6 +425,18 @@ don't we have to do this?
* when decrementing a reference count in a :c:member:`~PyTypeObject.tp_dealloc`
handler on a type which doesn't support cyclic garbage collection [#]_.

There is a much simpler way to reassign to ``self->first`` though, and that is by using :c:func:`Py_XSETREF` and :c:func:`Py_NewRef`::

if (first) {
Py_XSETREF(self->first, Py_NewRef(first));
}

:c:func:`Py_XSETREF` automatically handles the assignment to ``self->first`` and the decrementing of its reference count using :c:func:`Py_XDECREF` (in the correct way that was shown earlier). :c:func:`Py_NewRef` automatically handles the incrementing of the reference count for ``first``. We can also apply this to ``self->last`` and ``last``::

if (last) {
Py_XSETREF(self->last, Py_NewRef(last));
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not suggesting to use these functions at the first place (in the code above)? I'm not sure that this tutorial is the best place to explain how to handle reference counting in length.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think there should be a part for Py_SETREF/Py_XSETREF and Py_NewRef/Py_XNewRef in the reference counting part earlier in the tutorial and Py_SETREF/Py_XSETREF in the reference counting section since it isn't documented anywhere else yet. That way, this tutorial could just use Py_XSETREF and Py_NewRef instead of the 4-line snippet with no further explanation needed. I'll probably do that later if you agree with it.


We want to expose our instance variables as attributes. There are a
number of ways to do that. The simplest way is to define member definitions::

Expand Down