Why does Python create two refcounts for an object on creation?

memory, memory-management, python

Solution

Python counts the reference that is created within the `getrefcount` function when your argument is passed to the function.

Return the reference count of the object. The count returned is generally one higher than you might expect, because it includes the (temporary) reference as an argument to getrefcount().

From the Python documents

As for the garbage collection, Python will delete the reference to stored in the variable `o` when `del o` is called. Basically `sys.getrefcount` will always at least return `1` as it needs to create a reference to the argument within the function in order to count any other references to the passed argument. See the following output as an example that will hopefully shed some light on this.

>>> o = object()
>>> import sys
>>> sys.getrefcount(o)
2
>>> del o
>>> sys.getrefcount(o)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'o' is not defined

We can see that this reference has been removed, the garbage collector will now collect these on its next sweep as there is no available reference to the object created on the first line anymore. Discussion of Python garbage collection in relation to the `del` method.

Problem

So when I create an object without reference (as far as I can tell) why does Python maintain that there's a refcount for it? ``` >>> import sys >>> sys.getrefcount(object()) 1 ``` The following makes sense based on this extra refcount. ``` >>> o = object() >>> sys.getrefcount(o) 2 >>> l = list((o,)) >>> sys.getrefcount(o) 3 >>> del l[0] >>> sys.getrefcount(o) 2 ``` And it would seem that on ``` >>> del o ``` Python would Garbage Collect the object, but does it? If there's still a reference to it, where is that?

Original source