Reputation: 16085
I create a database connection in the __init__
method of a Python class and want to make sure that the connection is closed on object destruction.
It looks like I can do this in __del__()
or make the class a context manager and close the connection in __exit__()
. I wonder which one is more Pythonic.
Upvotes: 2
Views: 806
Reputation: 36362
It looks like I can do this in
__del__()
or make the class a context manager and close the connection in__exit__()
. I wonder which one is more Pythonic.
I won't comment on what's more "pythonic", since that is a highly subjective question.
However, Python doesn't make very strict guarantees on when a destructor is called, making the context/__exit__
approach the right one here.
Upvotes: 2