]> git.notmuchmail.org Git - notmuch/blobdiff - bindings/python/notmuch/database.py
python: implement the context manager protocol for database objects
[notmuch] / bindings / python / notmuch / database.py
index 6238b2891e066cf76a9361fc573509a287851124..533948c4491407597b8b0371eccbbb038300615c 100644 (file)
@@ -18,6 +18,7 @@ Copyright 2010 Sebastian Spaeth <Sebastian@SSpaeth.de>'
 """
 
 import os
+import codecs
 from ctypes import c_char_p, c_void_p, c_uint, c_long, byref, POINTER
 from notmuch.globals import (nmlib, STATUS, NotmuchError, NotInitializedError,
      NullPointerError, Enum, _str,
@@ -40,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
@@ -141,6 +146,9 @@ class Database(object):
         else:
             self.create(path)
 
+    def __del__(self):
+        self.close()
+
     def _assert_db_is_initialized(self):
         """Raises :exc:`NotInitializedError` if self._db is `None`"""
         if self._db is None:
@@ -192,6 +200,28 @@ class Database(object):
             raise NotmuchError(message="Could not open the specified database")
         self._db = res
 
+    _close = nmlib.notmuch_database_close
+    _close.argtypes = [NotmuchDatabaseP]
+    _close.restype = None
+
+    def close(self):
+        """Close and free the notmuch database if needed"""
+        if self._db is not None:
+            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()
@@ -530,15 +560,6 @@ class Database(object):
     def __repr__(self):
         return "'Notmuch DB " + self.get_path() + "'"
 
-    _close = nmlib.notmuch_database_close
-    _close.argtypes = [NotmuchDatabaseP]
-    _close.restype = None
-
-    def __del__(self):
-        """Close and free the notmuch database if needed"""
-        if self._db is not None:
-            self._close(self._db)
-
     def _get_user_default_db(self):
         """ Reads a user's notmuch config and returns his db location
 
@@ -553,11 +574,11 @@ class Database(object):
         config = SafeConfigParser()
         conf_f = os.getenv('NOTMUCH_CONFIG',
                            os.path.expanduser('~/.notmuch-config'))
-        config.read(conf_f)
+        config.readfp(codecs.open(conf_f, 'r', 'utf-8'))
         if not config.has_option('database', 'path'):
             raise NotmuchError(message="No DB path specified"
                                        " and no user default found")
-        return config.get('database', 'path').decode('utf-8')
+        return config.get('database', 'path')
 
     @property
     def db_p(self):