Reference counting while adding element to list

586 Views Asked by At

From listobject.h

I read this line:

"PyList_SetItem does not increment the new item's reference count, but does decrement the reference count of the item it replaces, if not nil. It does decrement the reference count if it is not inserted in the list. Similarly, PyList_GetItem does not increment the returned item's reference count."

But when i tested reference count of the element got increased.

>>> a = 'abc'
>>> sys.getrefcount(a)
3
>>> ls = [1,2]
>>> ls.append(a)
>>> ls
[1, 2, 'abc']
>>> sys.getrefcount(a)
4
>>> ls.insert(1,a)
>>> sys.getrefcount(a)
5
>>>

Please correct me if i wrong or explain me how it is ?

2

There are 2 best solutions below

0
On

The implementation of append knows about this quirk of PyList_SetItem and deals with the reference count increment.

This is really the only way it could work. Reference counting is really a facet of the implementation, and -- getrefcount notwithstanding -- not something Python programmers have to deal with.

To put it another way, you only need to worry about whether an API steals a reference or makes a new reference if you are writing an extension in C. If you stick to Python, you are safe.

1
On

That basically means that the caller to PyList_SetItem must take care of reference counting;

In the case of append, it is implemented in PyList_Append which is a simple wrapper arround app1(PyListObject *, PyObject *) and there it is in fact increasing the refrence count.

PyList_Insert also calls into ins1(PyListObject *, Py_ssize_t, PyObject *), which also increases the referene count.