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__()
__exit__closecall__del__. And don't get too wrapped up in protecting your users -- they are, after all, programmers and should be smart enough to use the API you have given them -- just make sure you have good docs, and the rest is on them.__del__in the close method is somewhat ugly as well. I think you are right - It's probably not a good idea to focus too much on users misusing the code. Especially when the code changes are rather hackish.