chiark / gitweb /
catacomb/pwsafe.py: Make `PW' be a context manager, and use it.
[catacomb-python] / catacomb / pwsafe.py
index 65aec712d09e5a2b62381d4ca88240db0e14b7f1..82f2a46f1df6952c202e18974b471cc8130b5408 100644 (file)
@@ -161,17 +161,17 @@ class PW (object):
   using the stored keys.
   """
 
-  def __init__(me, file, mode = 'r'):
+  def __init__(me, file, writep = False):
     """
     Initialize a PW object from the GDBM database in FILE.
 
-    MODE can be `r' for read-only access to the underlying database, or `w'
-    for read-write access.  Requests the database password from the Pixie,
+    If WRITEP is true, then allow write-access to the database; otherwise
+    allow read access only.  Requests the database password from the Pixie,
     which may cause interaction.
     """
 
     ## Open the database.
-    me.db = _G.open(file, mode)
+    me.db = _G.open(file, writep and 'w' or 'r')
 
     ## Find out what crypto to use.
     c = _C.gcciphers[me.db['cipher']]
@@ -299,4 +299,11 @@ class PW (object):
       if k[0] == '$': yield me.unpack(me.db[k])[0]
       k = me.db.nextkey(k)
 
+  ## Context protocol.
+
+  def __enter__(me):
+    return me
+  def __exit__(me, excty, excval, exctb):
+    me.db.close()
+
 ###----- That's all, folks --------------------------------------------------