Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 709
Russia Must Remove Putin Avatar asked Dec 11 '22 09:12

Russia Must Remove Putin


1 Answers

When you invoke sys.getrefcount(), a reference is generated for local use inside the function. getrefcount() will always add 1 to the actual count, because it counts its own internal ref.

like image 87
slezica Avatar answered Jan 05 '23 00:01

slezica