Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions Lib/shelve.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,9 +176,11 @@ def __del__(self):
def sync(self):
if self.writeback and self.cache:
self.writeback = False
for key, entry in self.cache.items():
self[key] = entry
self.writeback = True
try:
for key, entry in self.cache.items():
self[key] = entry
finally:
self.writeback = True
self.cache = {}
if hasattr(self.dict, 'sync'):
self.dict.sync()
Expand Down
19 changes: 19 additions & 0 deletions Lib/test/test_shelve.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,25 @@ def test_writeback_also_writes_immediately(self):
p2 = d[encodedkey]
self.assertNotEqual(p1, p2) # Write creates new object in store

def test_writeback_restored_after_failed_sync(self):
class Unpicklable:
def __reduce__(self):
raise RuntimeError('cannot pickle')

d = {}
with shelve.Shelf(d, writeback=True) as s:
s['key'] = []
s['key'].append(Unpicklable())
with self.assertRaises(RuntimeError):
s.sync()
self.assertTrue(s.writeback)
self.assertIn('key', s.cache)
s['key'].clear()
s['other'] = [1]
s['other'].append(2)
self.assertEqual(pickle.loads(d[b'key']), [])
self.assertEqual(pickle.loads(d[b'other']), [1, 2])

def test_with(self):
d1 = {}
with shelve.Shelf(d1, protocol=2, writeback=False) as s:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix :meth:`shelve.Shelf.sync` leaving *writeback* disabled when writing back
a cached entry raises an exception. Patch by Christian Aurich Zanettini Martins.
Loading