cpython/Lib/anydbm.py

52 lines
1.4 KiB
Python
Raw Normal View History

1995-08-10 16:24:30 -03:00
"""Generic interface to all dbm clones.
1995-02-09 13:18:10 -04:00
Instead of
import dbm
1995-08-10 16:24:30 -03:00
d = dbm.open(file, 'w', 0666)
1995-02-09 13:18:10 -04:00
use
import anydbm
d = anydbm.open(file)
1995-08-10 16:24:30 -03:00
The returned object is a dbhash, gdbm, dbm or dumbdbm object,
1995-02-09 13:18:10 -04:00
dependent on availability of the modules (tested in this order).
It has the following interface (key and data are strings):
d[key] = data # store data at key (may override data at
# existing key)
data = d[key] # retrieve data at key (raise KeyError if no
# such key)
del d[key] # delete data stored at key (raises KeyError
# if no such key)
flag = d.has_key(key) # true if the key exists
list = d.keys() # return a list of all existing keys (slow!)
Future versions may change the order in which implementations are
1995-08-10 16:24:30 -03:00
tested for existence, add interfaces to other dbm-like
implementations, and (in the presence of multiple implementations)
1995-02-09 13:18:10 -04:00
decide which module to use based upon the extension or contents of an
existing database file.
The open function has an optional second argument. This can be set to
1995-08-10 16:24:30 -03:00
'r' to open the database for reading only. The default is 'w', which
differs from the dbm default ('r') for historic reasons.
1995-02-09 13:18:10 -04:00
"""
1995-08-10 16:24:30 -03:00
_names = ['dbhash', 'gdbm', 'dbm', 'dumbdbm']
for _name in _names:
1995-02-09 13:18:10 -04:00
try:
1995-08-10 16:24:30 -03:00
exec "import %s; _mod = %s" % (_name, _name)
1995-02-09 13:18:10 -04:00
except ImportError:
1995-08-10 16:24:30 -03:00
continue
else:
break
else:
raise ImportError, "no dbm clone found; tried %s" % _names
def open(file, flag = 'w', mode = 0666):
return _mod.open(file, flag, mode)