Author: cito
Date: Sat May 12 16:21:20 2012
New Revision: 438

Log:
Allow connections and cursors to be used with the "with" statement (#46).

Modified:
   trunk/docs/changelog.txt
   trunk/module/pgdb.py

Modified: trunk/docs/changelog.txt
==============================================================================
--- trunk/docs/changelog.txt    Sat May 12 15:51:05 2012        (r437)
+++ trunk/docs/changelog.txt    Sat May 12 16:21:20 2012        (r438)
@@ -17,6 +17,8 @@
 - All DatabaseError instances now have a sqlstate attribute.
 - Open transactions are rolled back when pgdb connections are closed
   (as suggested by Peter Harris).
+- Connections and cursors can now be used with the "with" statement
+  (as suggested by Peter Harris).
 
 
 Version 4.0 (2009-01-01)

Modified: trunk/module/pgdb.py
==============================================================================
--- trunk/module/pgdb.py        Sat May 12 15:51:05 2012        (r437)
+++ trunk/module/pgdb.py        Sat May 12 16:21:20 2012        (r438)
@@ -222,9 +222,17 @@
         self.lastrowid = None
 
     def __iter__(self):
-        """Return self to make cursors compatible to the iteration protocol."""
+        """Make cursors compatible to the iteration protocol."""
         return self
 
+    def __enter__(self):
+        """Enter the runtime context for the cursor object."""
+        return self
+
+    def __exit__(self, et, ev, tb):
+        """Exit the runtime context for the cursor object."""
+        self.close()
+
     def _quote(self, val):
         """Quote value depending on its type."""
         if isinstance(val, (datetime, date, time, timedelta)):
@@ -446,6 +454,14 @@
         except Exception:
             raise _op_error("invalid connection")
 
+    def __enter__(self):
+        """Enter the runtime context for the connection object."""
+        return self
+
+    def __exit__(self, et, ev, tb):
+        """Exit the runtime context for the connection object."""
+        self.close()
+
     def close(self):
         """Close the connection object."""
         if self._cnx:
_______________________________________________
PyGreSQL mailing list
[email protected]
https://mail.vex.net/mailman/listinfo.cgi/pygresql

Reply via email to