planetp
planetp

Reputation: 16085

What's the preferred way to close a psycopg2 connection used by Python object?

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

Answers (1)

Marcus Müller
Marcus Müller

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

Related Questions