Search code examples
pythonmemory-managementgarbage-collectiondel

Difference between del x and x=None for reclaiming the memory?


I would like to reclaim memory of an instance variable in a class denoted by self.x below.

Should I use the command del self.x; or self.x=None? What would be their difference? Assuming that the command is to be put in a __del__ or __exit___ function of the class.


Solution

  • The first thing to understand is that neither del self.x nor self.x = None frees any many memory. What they both do is decrease the reference counter of the object referenced by self.x by one. Then if the counter of this object has reached 0 when the garbage collector will run then the memory will be freed

    For the difference between the two, you will not be able to read the value self.x since del self.x will remove x from the instance dictionary. self.x = None is simply reassigning self.x the object None.