4

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?

0

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

Comments

6

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.