Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does garbage collection in Python work with class methods?

class example:

    def exampleMethod(self):
        aVar = 'some string'
        return aVar

In this example, how does garbage collection work after each call to example.exampleMethod()? Will aVar be deallocated once the method returns?

like image 242
davidmytton Avatar asked Sep 03 '25 03:09

davidmytton


1 Answers

The variable is never deallocated.

The object (in this case a string, with a value of 'some string' is reused again and again, so that object can never be deallocated.

Objects are deallocated when no variable refers to the object. Think of this.

a = 'hi mom'
a = 'next value'

In this case, the first object (a string with the value 'hi mom') is no longer referenced anywhere in the script when the second statement is executed. The object ('hi mom') can be removed from memory.

like image 145
S.Lott Avatar answered Sep 05 '25 01:09

S.Lott