Initial commit of OpenSPARC T2 design and verification files.
[OpenSPARC-T2-DV] / tools / src / nas,5.n2.os.2 / lib / python / lib / python2.4 / anydbm.py
CommitLineData
86530b38
AT
1"""Generic interface to all dbm clones.
2
3Instead of
4
5 import dbm
6 d = dbm.open(file, 'w', 0666)
7
8use
9
10 import anydbm
11 d = anydbm.open(file, 'w')
12
13The returned object is a dbhash, gdbm, dbm or dumbdbm object,
14dependent on the type of database being opened (determined by whichdb
15module) in the case of an existing dbm. If the dbm does not exist and
16the create or new flag ('c' or 'n') was specified, the dbm type will
17be determined by the availability of the modules (tested in the above
18order).
19
20It has the following interface (key and data are strings):
21
22 d[key] = data # store data at key (may override data at
23 # existing key)
24 data = d[key] # retrieve data at key (raise KeyError if no
25 # such key)
26 del d[key] # delete data stored at key (raises KeyError
27 # if no such key)
28 flag = key in d # true if the key exists
29 list = d.keys() # return a list of all existing keys (slow!)
30
31Future versions may change the order in which implementations are
32tested for existence, add interfaces to other dbm-like
33implementations.
34
35The open function has an optional second argument. This can be 'r',
36for read-only access, 'w', for read-write access of an existing
37database, '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'.
39
40Note: 'r' and 'w' fail if the database doesn't exist; 'c' creates it
41only if it doesn't exist; and 'n' always creates a new database.
42
43"""
44
45class error(Exception):
46 pass
47
48_names = ['dbhash', 'gdbm', 'dbm', 'dumbdbm']
49_errors = [error]
50_defaultmod = None
51
52for _name in _names:
53 try:
54 _mod = __import__(_name)
55 except ImportError:
56 continue
57 if not _defaultmod:
58 _defaultmod = _mod
59 _errors.append(_mod.error)
60
61if not _defaultmod:
62 raise ImportError, "no dbm clone found; tried %s" % _names
63
64error = tuple(_errors)
65
66def open(file, flag = 'r', mode = 0666):
67 # guess the type of an existing database
68 from whichdb import whichdb
69 result=whichdb(file)
70 if result is None:
71 # db doesn't exist
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
75 mod = _defaultmod
76 else:
77 raise error, "need 'c' or 'n' flag to open new db"
78 elif result == "":
79 # db type cannot be determined
80 raise error, "db type could not be determined"
81 else:
82 mod = __import__(result)
83 return mod.open(file, flag, mode)