From 5e01c47818f86511afaf2d016194bc77bca5bf54 Mon Sep 17 00:00:00 2001 From: Daniele Varrazzo Date: Sun, 7 Apr 2019 11:19:56 +0100 Subject: [PATCH] Highlight in docs that the context manager doesn't close the connection Code as in #889 is not robust, but the behaviour is actually counter-intuitive. --- doc/src/usage.rst | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/doc/src/usage.rst b/doc/src/usage.rst index 07e7d0c8..48744ef7 100644 --- a/doc/src/usage.rst +++ b/doc/src/usage.rst @@ -797,9 +797,7 @@ is rolled back. When a cursor exits the ``with`` block it is closed, releasing any resource eventually associated with it. The state of the transaction is not affected. -Note that, unlike file objects or other resources, exiting the connection's -``with`` block *doesn't close the connection* but only the transaction -associated with it: a connection can be used in more than a ``with`` statement +A connection can be used in more than a ``with`` statement and each ``with`` block is effectively wrapped in a separate transaction:: conn = psycopg2.connect(DSN) @@ -814,6 +812,18 @@ and each ``with`` block is effectively wrapped in a separate transaction:: conn.close() +.. warning:: + + Unlike file objects or other resources, exiting the connection's + ``with`` block **doesn't close the connection**, but only the transaction + associated to it. If you want to make sure the connection is closed after + a certain point, you should still use a try-catch block:: + + conn = psycopg2.connect(DSN) + try: + # connection usage + finally: + conn.close() .. index::