Asker
Asker

Reputation: 1685

Under what conditions does the reference count in Python increment/decrement?

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

Answers (1)

DarrylG
DarrylG

Reputation: 17156

To answer your question:

Why do reference cycles prevent the count from going to 0?

Reference

Things which increase reference count includes:

  1. assignment operator
  2. argument passing
  3. appending an object to a list

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

Related Questions