PageRenderTime 48ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/anydbm.py

https://bitbucket.org/dac_io/pypy
Python | 85 lines | 78 code | 0 blank | 7 comment | 5 complexity | 42a7ed8e67feb0ef553066094648c346 MD5 | raw file
  1. """Generic interface to all dbm clones.
  2. Instead of
  3. import dbm
  4. d = dbm.open(file, 'w', 0666)
  5. use
  6. import anydbm
  7. d = anydbm.open(file, 'w')
  8. The returned object is a dbhash, gdbm, dbm or dumbdbm object,
  9. dependent on the type of database being opened (determined by whichdb
  10. module) in the case of an existing dbm. If the dbm does not exist and
  11. the create or new flag ('c' or 'n') was specified, the dbm type will
  12. be determined by the availability of the modules (tested in the above
  13. order).
  14. It has the following interface (key and data are strings):
  15. d[key] = data # store data at key (may override data at
  16. # existing key)
  17. data = d[key] # retrieve data at key (raise KeyError if no
  18. # such key)
  19. del d[key] # delete data stored at key (raises KeyError
  20. # if no such key)
  21. flag = key in d # true if the key exists
  22. list = d.keys() # return a list of all existing keys (slow!)
  23. Future versions may change the order in which implementations are
  24. tested for existence, and add interfaces to other dbm-like
  25. implementations.
  26. """
  27. class error(Exception):
  28. pass
  29. _names = ['dbhash', 'gdbm', 'dbm', 'dumbdbm']
  30. _errors = [error]
  31. _defaultmod = None
  32. for _name in _names:
  33. try:
  34. _mod = __import__(_name)
  35. except ImportError:
  36. continue
  37. if not _defaultmod:
  38. _defaultmod = _mod
  39. _errors.append(_mod.error)
  40. if not _defaultmod:
  41. raise ImportError, "no dbm clone found; tried %s" % _names
  42. error = tuple(_errors)
  43. def open(file, flag='r', mode=0666):
  44. """Open or create database at path given by *file*.
  45. Optional argument *flag* can be 'r' (default) for read-only access, 'w'
  46. for read-write access of an existing database, 'c' for read-write access
  47. to a new or existing database, and 'n' for read-write access to a new
  48. database.
  49. Note: 'r' and 'w' fail if the database doesn't exist; 'c' creates it
  50. only if it doesn't exist; and 'n' always creates a new database.
  51. """
  52. # guess the type of an existing database
  53. from whichdb import whichdb
  54. result=whichdb(file)
  55. if result is None:
  56. # db doesn't exist
  57. if 'c' in flag or 'n' in flag:
  58. # file doesn't exist and the new
  59. # flag was used so use default type
  60. mod = _defaultmod
  61. else:
  62. raise error, "need 'c' or 'n' flag to open new db"
  63. elif result == "":
  64. # db type cannot be determined
  65. raise error, "db type could not be determined"
  66. else:
  67. mod = __import__(result)
  68. return mod.open(file, flag, mode)