The __del__
method, it will be called when the object is garbage collected. Note that it isn't necessarily guaranteed to be called though. The following code by itself won't necessarily do it:
del obj
The reason being that del
just decrements the reference count by one. If something else has a reference to the object, __del__
won't get called.
There are a few caveats to using __del__
though. Generally, they usually just aren't very useful. It sounds to me more like you want to use a close method or maybe a with statement.
See the python documentation on __del__
methods.
One other thing to note: __del__
methods can inhibit garbage collection if overused. In particular, a circular reference that has more than one object with a __del__
method won't get garbage collected. This is because the garbage collector doesn't know which one to call first. See the documentation on the gc module for more info.