]> git.notmuchmail.org Git - notmuch/commitdiff
python: implement the context manager protocol for database objects
authorJustus Winter <4winter@informatik.uni-hamburg.de>
Wed, 15 Feb 2012 21:41:16 +0000 (22:41 +0100)
committerJustus Winter <4winter@informatik.uni-hamburg.de>
Wed, 15 Feb 2012 21:41:16 +0000 (22:41 +0100)
Signed-off-by: Justus Winter <4winter@informatik.uni-hamburg.de>
bindings/python/notmuch/database.py

index d0e38ddab8c0f7b276c46ab8d5b463f0436dbd05..533948c4491407597b8b0371eccbbb038300615c 100644 (file)
@@ -41,6 +41,10 @@ class Database(object):
     :exc:`XapianError` as the underlying database has been
     modified. Close and reopen the database to continue working with it.
 
+    :class:`Database` objects implement the context manager protocol
+    so you can use the :keyword:`with` statement to ensure that the
+    database is properly closed.
+
     .. note::
 
         Any function in this class can and will throw an
@@ -206,6 +210,18 @@ class Database(object):
             self._close(self._db)
             self._db = None
 
+    def __enter__(self):
+        '''
+        Implements the context manager protocol.
+        '''
+        return self
+
+    def __exit__(self, exc_type, exc_value, traceback):
+        '''
+        Implements the context manager protocol.
+        '''
+        self.close()
+
     def get_path(self):
         """Returns the file path of an open database"""
         self._assert_db_is_initialized()