From: Raymond Hettinger Date: Fri, 25 Jul 2008 18:43:33 +0000 (+0000) Subject: Issue 1592: Better error reporting for operations on closed shelves. X-Git-Tag: v2.6b3~230 X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=8c664e8628ace6a9f3b64980af262b67cd7f3e59;p=python Issue 1592: Better error reporting for operations on closed shelves. --- diff --git a/Lib/shelve.py b/Lib/shelve.py index 7a75445b0b..2a430f374b 100644 --- a/Lib/shelve.py +++ b/Lib/shelve.py @@ -73,6 +73,16 @@ import warnings __all__ = ["Shelf","BsdDbShelf","DbfilenameShelf","open"] +class _ClosedDict(UserDict.DictMixin): + 'Marker for a closed dict. Access attempts raise a ValueError.' + + def closed(self, *args): + raise ValueError('invalid operation on closed shelf') + __getitem__ = __setitem__ = __delitem__ = keys = closed + + def __repr__(self): + return '' + class Shelf(UserDict.DictMixin): """Base class for shelf implementations. @@ -136,7 +146,7 @@ class Shelf(UserDict.DictMixin): self.dict.close() except AttributeError: pass - self.dict = 0 + self.dict = _ClosedDict() def __del__(self): if not hasattr(self, 'writeback'): diff --git a/Lib/test/test_shelve.py b/Lib/test/test_shelve.py index ffd2120372..ffcc98da56 100644 --- a/Lib/test/test_shelve.py +++ b/Lib/test/test_shelve.py @@ -8,6 +8,21 @@ class TestCase(unittest.TestCase): fn = "shelftemp" + os.extsep + "db" + def test_close(self): + d1 = {} + s = shelve.Shelf(d1, protocol=2, writeback=False) + s['key1'] = [1,2,3,4] + self.assertEqual(s['key1'], [1,2,3,4]) + self.assertEqual(len(s), 1) + s.close() + self.assertRaises(ValueError, len, s) + try: + s['key1'] + except ValueError: + pass + else: + self.fail('Closed shelf should not find a key') + def test_ascii_file_shelf(self): try: s = shelve.open(self.fn, protocol=0) diff --git a/Misc/NEWS b/Misc/NEWS index 53c680d694..87ef02d325 100644 --- a/Misc/NEWS +++ b/Misc/NEWS @@ -26,6 +26,9 @@ Core and Builtins Library ------- +- Issue 1592: Improve error reporting when operations are attempted + on a closed shelf. + - Deprecate the "ast" parser function aliases. - Issue #3120: On 64-bit Windows the subprocess module was truncating handles.