3 ms·
I consider Python destructors either bugs or unnecessary. The reason, which the article neglects to consider, is that there are always cases where the destructo
by stubish 8y ago
I consider Python destructors either bugs or unnecessary. The reason, which the article neglects to consider, is that there are always cases where the destructors are not called. If you are relying on destructors running to do required cleanup (eg. removing temporary files), you have a bug. If you are not relying on the destructors running (eg. trace logging, closing database connections), then they are unnecessary.
They are also a source of latent bugs, which can eventually bite you as your code ages. For example, did you know it is unsafe to reference module level attributes from a destructor? Lets say your destructor does some simple cleanup using shutil.rmtree. This only works if the object's destructor is invoked before the shutil module is garbage collected at program termination. It might work now, but change the imports around or delay when the object is cleaned up (say, sticking it in a cache), and your program now spits out NameError tracebacks on termination. Which thankfully are just noise, since exceptions in destructors are ignored. Which itself is another gotcha, since you might actually want your program to exit with a failure code if it is failing.
So yes, avoid temptation and never use Python destructors. Even if you use them for the trivial things they allow or the baroque constructs required to do more complex things safely, the next person working on your code won't.