I have an object with an internal database connection that's active throughout its lifetime. At the end of the program's run, the connection has to be committed and closed. So far I've used an explicit close
method, but this is somewhat cumbersome, especially when exceptions can happen in the calling code.
I'm considering using the __del__
method for closing, but after some reading online I have concerns. Is this a valid usage pattern? Can I be sure that the internal resources will be freed in __del__
correctly?
This discussion raised a similar question but found no satisfactory answer. I don't want to have an explicit close
method, and using with
isn't an option, because my object isn't used as simply as open-play-close, but is kept as a member of another, larger object, that uses it while running in a GUI.
C++ has perfectly working destructors where one can free resources safely, so I would imagine Python has something agreed-upon too. For some reason it seems not to be the case, and many in the community vow against __del__
. What's the alternative, then?