Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python how to release the memory for class object after processing it?

I use None keyword to delete a class object.

 class demo:
   class members

 obj= demo()
 some processing
 obj=None

By using None,will the memory be released?

I found that del can also be used to delete a class object.Or I should use

   del obj

to release the memory?

What is the difference between using del and None in deleting a class object and releasing the memory or invoking garbage collection?

like image 652
titto.sebastian Avatar asked Mar 27 '15 10:03

titto.sebastian


1 Answers

Python objects are released when there are no more references to the object.

Rebinding obj to None would decrease the reference count to the object, and so would del obj. In both cases, the instance would be cleared if obj was the last reference to it.

The difference then is how you can use obj afterwards. Rebinding retains the variable (it is now bound to None), del removes it altogether and you'd get a NameError. What you pick is your choice, it won't have influence on how the instance is cleared from memory.

like image 78
Martijn Pieters Avatar answered Oct 24 '22 10:10

Martijn Pieters