Reputation: 1685
I know that in Python, garbage collection for an object is triggered when an object's reference count reaches 0.
https://docs.python.org/3.8/c-api/intro.html#objects-types-and-reference-counts
But I'm struggling to understand what exactly are the conditions that trigger the increment/decrementing of the reference count.
In particular,
(1) I know the count is incremented for each reference to an object... but I don't know exactly what is meant by a reference in the context of Python. I'm struggling to understand how references differ from, say, names or variables. What exactly is a reference in Python? (examples extra-appreciated)
and
(2) What are the conditions which trigger the decrementing of the reference count?
Upvotes: 1
Views: 1689
Reputation: 17156
To answer your question:
Why do reference cycles prevent the count from going to 0?
Things which increase reference count includes:
Consider the following code:
lst = [] # assignment => (ref count + 1) for related object
lst.append(lst) # append to list => (ref count + 1) for related object
After the two steps above -> reference count = 2 (+1 for each step)
However, this has created a reference cycle.
del lst # decreases reference count by 1
Now, reference count = 1.
But, no variables refer to this object so the reference count won't change.
And, regular garbage collection won't remove it since ref count > 0.
So with regular garbage collection, this leads to what's referred to as a "memory leak" (i.e. memory that's not referred to but can't be released).
Upvotes: 4