cpython/Lib/anydbm.py

86 lines
2.6 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
2001-01-14 14:09:23 -04:00
import dbm
d = dbm.open(file, 'w', 0666)
1995-02-09 13:18:10 -04:00
use
2001-01-14 14:09:23 -04:00
import anydbm
d = anydbm.open(file, 'w')
1995-02-09 13:18:10 -04:00
1995-08-10 16:24:30 -03:00
The returned object is a dbhash, gdbm, dbm or dumbdbm object,
dependent on the type of database being opened (determined by whichdb
module) in the case of an existing dbm. If the dbm does not exist and
the create or new flag ('c' or 'n') was specified, the dbm type will
be determined by the availability of the modules (tested in the above
order).
1995-02-09 13:18:10 -04:00
It has the following interface (key and data are strings):
2001-01-14 14:09:23 -04:00
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 = key in d # true if the key exists
2001-01-14 14:09:23 -04:00
list = d.keys() # return a list of all existing keys (slow!)
1995-02-09 13:18:10 -04:00
Future versions may change the order in which implementations are
2011-04-30 21:02:30 -03:00
tested for existence, and add interfaces to other dbm-like
implementations.
1995-02-09 13:18:10 -04:00
"""
class error(Exception):
pass
1995-08-10 16:24:30 -03:00
_names = ['dbhash', 'gdbm', 'dbm', 'dumbdbm']
_errors = [error]
_defaultmod = None
1995-08-10 16:24:30 -03:00
for _name in _names:
2001-01-14 14:09:23 -04:00
try:
_mod = __import__(_name)
except ImportError:
continue
if not _defaultmod:
_defaultmod = _mod
_errors.append(_mod.error)
if not _defaultmod:
2001-01-14 14:09:23 -04:00
raise ImportError, "no dbm clone found; tried %s" % _names
1996-01-25 14:26:57 -04:00
error = tuple(_errors)
1996-01-25 14:26:57 -04:00
2011-04-30 21:02:30 -03:00
def open(file, flag='r', mode=0666):
"""Open or create database at path given by *file*.
Optional argument *flag* can be 'r' (default) for read-only access, 'w'
for read-write access of an existing database, 'c' for read-write access
to a new or existing database, and 'n' for read-write access to a new
database.
Note: 'r' and 'w' fail if the database doesn't exist; 'c' creates it
only if it doesn't exist; and 'n' always creates a new database.
"""
2001-01-14 14:09:23 -04:00
# guess the type of an existing database
from whichdb import whichdb
result=whichdb(file)
if result is None:
# db doesn't exist
if 'c' in flag or 'n' in flag:
# file doesn't exist and the new
# flag was used so use default type
mod = _defaultmod
else:
raise error, "need 'c' or 'n' flag to open new db"
elif result == "":
# db type cannot be determined
raise error, "db type could not be determined"
else:
mod = __import__(result)
return mod.open(file, flag, mode)