I have been thinking about how I write classes in Python. More specifically how the constructor is implemented and how the object should be destroyed. I don\'t want to rely
If you are sure you will not go into cyclic references, then using __del__
in that way is OK: as soon as the reference count goes to zero, the CPython VM will call that method and destroy the object.
If you plan to use cyclic references - please think it very thoroughly, and check if weak references may help; in many cases, cyclic references are a first symptom of bad design.
If you have no control on the way your object is going to be used, then using __del__
may not be safe.
If you plan to use JPython or IronPython, __del__
is unreliable at all, because final object destruction will happen at garbage collection, and that's something you cannot control.
In sum, in my opinion, __del__
is usually perfectly safe and good; however, in many situation it could be better to make a step back, and try to look at the problem from a different perspective; a good use of try/except and of with contexts may be a more pythonic solution.