Python: "old" memory is free when new content is assigned to a variable?

If a variable is assigned any new content, will the memory allocated for the "old content" be "correctly" free? For example, in the following script, the memory for the variable "a", as an array of zeros, will be free after "a" has been assigned some new stuff

import numpy
a = numpy.zeros(1000)
a = a+1

      

I wish Python was smart enough to do everything cleanly using what is called "garbage collection", which I never know how to read. Any confirmation? I would appreciate.

+3


source to share


2 answers


Eventually, the old memory will be freed, although you cannot predict when this will happen. It depends on the Python implementation and many other factors.

However, for the example you gave and the CPython implementation, the old array should be garbage collected at assignment time.



(Note that NumPy arrays are a particularly tricky example to discuss garbage collection behavior.)

+7


source


You can find the answer by playing around with the gc module (and possibly with finalization). It provides the ability to disable the collector, adjust the collection rate, and set debug parameters. It also provides access to inaccessible objects that the collector has found but cannot release. See http://docs.python.org/library/gc.html



+1


source







All Articles