When You No Longer Need That Object * Dealing With Garbage in Python
Briefly

Python treats almost everything as objects and manages object lifetime automatically through garbage collection. CPython handles object reclamation behind the scenes so programmers rarely need to explicitly free memory. Classes can define a __del__() finaliser method that is invoked immediately before an object is destroyed and removed from memory. The __del__() method is not equivalent to the del statement; __del__() does not define behavior of del but serves as a cleanup hook. Printing inside __del__() reveals when the interpreter is about to remove an object. Providing explicit unique identifiers on objects can aid clarity when observing object creation and destruction in the REPL.
But we don't often talk about how to get rid of objects from memory in Python. And there's a reason for this: Python deals with this task behind the scenes so that you, the programmer, don't need to be concerned about removing objects from memory. But that's not a good enough reason to ignore what's happening when Python decides to toss an object away!
Now, the name of this special method could be slightly misleading. The .__del__() special method is not directly connected to the del keyword in the same way that .__len__() is connected to len() or .__iter__() is connected to iter(), say. The .__del__() special method doesn't define what happens when you use del on the object. Instead, .__del__() is a finaliser: it's called just before an object is destroyed-just before it's removed from memory.
Read at Thepythoncodingstack
[
|
]