Skip to content Skip to sidebar Skip to footer

Reference Counting Using Pydict_setitemstring

I'm wondering how memory management/reference counting works when a new value is set into an existing field within a PyDict (within a C extension). For instance, assume a dictionar

Solution 1:

The ref count of the old value is decremented automatically by logic of PyList_SetItem function. You shouldn't be decrementing the old value by yourself.

If you want to know details, take a look at CPython source code, specifically at the Objects/dictobject.c file.

1) The PyDict_SetItemString()

https://github.com/python/cpython/blob/c8e7c5a/Objects/dictobject.c#L3250-L3262

It it's a thin wrapper around PyDict_SetItem()

2) The PyDict_SetItem()

https://github.com/python/cpython/blob/c8e7c5a/Objects/dictobject.c#L1537-L1565

Is still quite simple and it's obvious that all the heavy-lifting related to inserting/replacing values in a dict is actually done by insertdict().

3) The insertdict()

https://github.com/python/cpython/blob/c8e7c5a/Objects/dictobject.c#L1097-L1186

is the function which gives us the answer. In this function you can find the crucial code and especially the call:

Py_XDECREF(old_value); /* which **CAN** re-enter (see issue #22653) */

which decrements the ref count of old value.

Post a Comment for "Reference Counting Using Pydict_setitemstring"