diff options
Diffstat (limited to 'Lib/dbm/dumb.py')
-rw-r--r-- | Lib/dbm/dumb.py | 123 |
1 files changed, 76 insertions, 47 deletions
diff --git a/Lib/dbm/dumb.py b/Lib/dbm/dumb.py index cfb9123..63bc329 100644 --- a/Lib/dbm/dumb.py +++ b/Lib/dbm/dumb.py @@ -21,6 +21,7 @@ is read when the database is opened, and some updates rewrite the whole index) """ +import ast as _ast import io as _io import os as _os import collections @@ -29,7 +30,7 @@ __all__ = ["error", "open"] _BLOCKSIZE = 512 -error = IOError +error = OSError class _Database(collections.MutableMapping): @@ -67,10 +68,11 @@ class _Database(collections.MutableMapping): # Mod by Jack: create data file if needed try: f = _io.open(self._datfile, 'r', encoding="Latin-1") - except IOError: - f = _io.open(self._datfile, 'w', encoding="Latin-1") - self._chmod(self._datfile) - f.close() + except OSError: + with _io.open(self._datfile, 'w', encoding="Latin-1") as f: + self._chmod(self._datfile) + else: + f.close() self._update() # Read directory file into the in-memory index dict. @@ -78,15 +80,15 @@ class _Database(collections.MutableMapping): self._index = {} try: f = _io.open(self._dirfile, 'r', encoding="Latin-1") - except IOError: + except OSError: pass else: - for line in f: - line = line.rstrip() - key, pos_and_siz_pair = eval(line) - key = key.encode('Latin-1') - self._index[key] = pos_and_siz_pair - f.close() + with f: + for line in f: + line = line.rstrip() + key, pos_and_siz_pair = _ast.literal_eval(line) + key = key.encode('Latin-1') + self._index[key] = pos_and_siz_pair # Write the index dict to the directory file. The original directory # file (if any) is renamed with a .bak extension first. If a .bak @@ -100,32 +102,36 @@ class _Database(collections.MutableMapping): try: self._os.unlink(self._bakfile) - except self._os.error: + except OSError: pass try: self._os.rename(self._dirfile, self._bakfile) - except self._os.error: + except OSError: pass - f = self._io.open(self._dirfile, 'w', encoding="Latin-1") - self._chmod(self._dirfile) - for key, pos_and_siz_pair in self._index.items(): - # Use Latin-1 since it has no qualms with any value in any - # position; UTF-8, though, does care sometimes. - f.write("%r, %r\n" % (key.decode('Latin-1'), pos_and_siz_pair)) - f.close() + with self._io.open(self._dirfile, 'w', encoding="Latin-1") as f: + self._chmod(self._dirfile) + for key, pos_and_siz_pair in self._index.items(): + # Use Latin-1 since it has no qualms with any value in any + # position; UTF-8, though, does care sometimes. + entry = "%r, %r\n" % (key.decode('Latin-1'), pos_and_siz_pair) + f.write(entry) sync = _commit + def _verify_open(self): + if self._index is None: + raise error('DBM object has already been closed') + def __getitem__(self, key): if isinstance(key, str): key = key.encode('utf-8') + self._verify_open() pos, siz = self._index[key] # may raise KeyError - f = _io.open(self._datfile, 'rb') - f.seek(pos) - dat = f.read(siz) - f.close() + with _io.open(self._datfile, 'rb') as f: + f.seek(pos) + dat = f.read(siz) return dat # Append val to the data file, starting at a _BLOCKSIZE-aligned @@ -133,14 +139,13 @@ class _Database(collections.MutableMapping): # to get to an aligned offset. Return pair # (starting offset of val, len(val)) def _addval(self, val): - f = _io.open(self._datfile, 'rb+') - f.seek(0, 2) - pos = int(f.tell()) - npos = ((pos + _BLOCKSIZE - 1) // _BLOCKSIZE) * _BLOCKSIZE - f.write(b'\0'*(npos-pos)) - pos = npos - f.write(val) - f.close() + with _io.open(self._datfile, 'rb+') as f: + f.seek(0, 2) + pos = int(f.tell()) + npos = ((pos + _BLOCKSIZE - 1) // _BLOCKSIZE) * _BLOCKSIZE + f.write(b'\0'*(npos-pos)) + pos = npos + f.write(val) return (pos, len(val)) # Write val to the data file, starting at offset pos. The caller @@ -148,10 +153,9 @@ class _Database(collections.MutableMapping): # pos to hold val, without overwriting some other value. Return # pair (pos, len(val)). def _setval(self, pos, val): - f = _io.open(self._datfile, 'rb+') - f.seek(pos) - f.write(val) - f.close() + with _io.open(self._datfile, 'rb+') as f: + f.seek(pos) + f.write(val) return (pos, len(val)) # key is a new key whose associated value starts in the data file @@ -159,10 +163,9 @@ class _Database(collections.MutableMapping): # the in-memory index dict, and append one to the directory file. def _addkey(self, key, pos_and_siz_pair): self._index[key] = pos_and_siz_pair - f = _io.open(self._dirfile, 'a', encoding="Latin-1") - self._chmod(self._dirfile) - f.write("%r, %r\n" % (key.decode("Latin-1"), pos_and_siz_pair)) - f.close() + with _io.open(self._dirfile, 'a', encoding="Latin-1") as f: + self._chmod(self._dirfile) + f.write("%r, %r\n" % (key.decode("Latin-1"), pos_and_siz_pair)) def __setitem__(self, key, val): if isinstance(key, str): @@ -173,6 +176,7 @@ class _Database(collections.MutableMapping): val = val.encode('utf-8') elif not isinstance(val, (bytes, bytearray)): raise TypeError("values must be bytes or strings") + self._verify_open() if key not in self._index: self._addkey(key, self._addval(val)) else: @@ -200,6 +204,7 @@ class _Database(collections.MutableMapping): def __delitem__(self, key): if isinstance(key, str): key = key.encode('utf-8') + self._verify_open() # The blocks used by the associated value are lost. del self._index[key] # XXX It's unclear why we do a _commit() here (the code always @@ -209,26 +214,44 @@ class _Database(collections.MutableMapping): self._commit() def keys(self): - return list(self._index.keys()) + try: + return list(self._index) + except TypeError: + raise error('DBM object has already been closed') from None def items(self): + self._verify_open() return [(key, self[key]) for key in self._index.keys()] def __contains__(self, key): if isinstance(key, str): key = key.encode('utf-8') - return key in self._index + try: + return key in self._index + except TypeError: + if self._index is None: + raise error('DBM object has already been closed') from None + else: + raise def iterkeys(self): - return iter(self._index.keys()) + try: + return iter(self._index) + except TypeError: + raise error('DBM object has already been closed') from None __iter__ = iterkeys def __len__(self): - return len(self._index) + try: + return len(self._index) + except TypeError: + raise error('DBM object has already been closed') from None def close(self): - self._commit() - self._index = self._datfile = self._dirfile = self._bakfile = None + try: + self._commit() + finally: + self._index = self._datfile = self._dirfile = self._bakfile = None __del__ = close @@ -236,6 +259,12 @@ class _Database(collections.MutableMapping): if hasattr(self._os, 'chmod'): self._os.chmod(file, self._mode) + def __enter__(self): + return self + + def __exit__(self, *args): + self.close() + def open(file, flag=None, mode=0o666): """Open the database file, filename, and return corresponding object. |