Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit ef08fb1

Browse files
committed
Issue #13896: Make shelf instances work with 'with' as context managers.
Original patch by Filip Gruszczyński.
1 parent dc22587 commit ef08fb1

3 files changed

Lines changed: 23 additions & 0 deletions

File tree

Lib/shelve.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,12 @@ def __delitem__(self, key):
131131
except KeyError:
132132
pass
133133

134+
def __enter__(self):
135+
return self
136+
137+
def __exit__(self, type, value, traceback):
138+
self.close()
139+
134140
def close(self):
135141
self.sync()
136142
try:
@@ -147,6 +153,7 @@ def close(self):
147153
def __del__(self):
148154
if not hasattr(self, 'writeback'):
149155
# __init__ didn't succeed, so don't bother closing
156+
# see http://bugs.python.org/issue1339007 for details
150157
return
151158
self.close()
152159

Lib/test/test_shelve.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,19 @@ def test_writeback_also_writes_immediately(self):
148148
p2 = d[encodedkey]
149149
self.assertNotEqual(p1, p2) # Write creates new object in store
150150

151+
def test_with(self):
152+
d1 = {}
153+
with shelve.Shelf(d1, protocol=2, writeback=False) as s:
154+
s['key1'] = [1,2,3,4]
155+
self.assertEqual(s['key1'], [1,2,3,4])
156+
self.assertEqual(len(s), 1)
157+
self.assertRaises(ValueError, len, s)
158+
try:
159+
s['key1']
160+
except ValueError:
161+
pass
162+
else:
163+
self.fail('Closed shelf should not find a key')
151164

152165
from test import mapping_tests
153166

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,9 @@ Core and Builtins
3939
Library
4040
-------
4141

42+
- Issue #13896: Make shelf instances work with 'with' as context managers.
43+
Original patch by Filip Gruszczyński.
44+
4245
- Issue #15417: Add support for csh and fish in venv activation scripts.
4346

4447
- Issue #16123: IDLE - deprecate running without a subprocess.

0 commit comments

Comments
 (0)