I'm working on a connection-like object which implements a context manager. Writing something like this is strongly encouraged:
with MyConnection() as con:
# do stuff
Of course one can do this as well:
con = MyConnection()
# do stuff
con.close()
But failing to close the connection is rather problematic. So closing in the __del__()
seems like a good idea:
def __del__(self):
self.close()
This looks quite nice, but sometimes leads to errors:
Exception ignored in: [...]
Traceback (most recent call last):
File "...", line xxx, in __del__()
TypeError: 'NoneType' object is not callable
It appears as if sometimes the close method is already destroyed, when __del__()
is called.
So I'm looking for a nice way to encourage python to close the connection properly on destruction. If possible I would like to avoid code duplication in close()
and __del__()