1 """Generic interface to all dbm clones.
6 d = dbm.open(file, 'w', 0666)
11 d = anydbm.open(file, 'w')
13 The returned object is a dbhash, gdbm, dbm or dumbdbm object,
14 dependent on the type of database being opened (determined by whichdb
15 module) in the case of an existing dbm. If the dbm does not exist and
16 the create or new flag ('c' or 'n') was specified, the dbm type will
17 be determined by the availability of the modules (tested in the above
20 It has the following interface (key and data are strings):
22 d[key] = data # store data at key (may override data at
24 data = d[key] # retrieve data at key (raise KeyError if no
26 del d[key] # delete data stored at key (raises KeyError
28 flag = key in d # true if the key exists
29 list = d.keys() # return a list of all existing keys (slow!)
31 Future versions may change the order in which implementations are
32 tested for existence, add interfaces to other dbm-like
35 The open function has an optional second argument. This can be 'r',
36 for read-only access, 'w', for read-write access of an existing
37 database, 'c' for read-write access to a new or existing database, and
38 'n' for read-write access to a new database. The default is 'r'.
40 Note: 'r' and 'w' fail if the database doesn't exist; 'c' creates it
41 only if it doesn't exist; and 'n' always creates a new database.
45 class error(Exception):
48 _names
= ['dbhash', 'gdbm', 'dbm', 'dumbdbm']
54 _mod
= __import__(_name
)
59 _errors
.append(_mod
.error
)
62 raise ImportError, "no dbm clone found; tried %s" % _names
64 error
= tuple(_errors
)
66 def open(file, flag
= 'r', mode
= 0666):
67 # guess the type of an existing database
68 from whichdb
import whichdb
72 if 'c' in flag
or 'n' in flag
:
73 # file doesn't exist and the new
74 # flag was used so use default type
77 raise error
, "need 'c' or 'n' flag to open new db"
79 # db type cannot be determined
80 raise error
, "db type could not be determined"
82 mod
= __import__(result
)
83 return mod
.open(file, flag
, mode
)