mirror of https://github.com/python/cpython
Issue #13896: Make shelf instances work with 'with' as context managers.
Original patch by Filip Gruszczyński.
This commit is contained in:
parent
dc22587df2
commit
ef08fb1f04
|
@ -131,6 +131,12 @@ class Shelf(collections.MutableMapping):
|
||||||
except KeyError:
|
except KeyError:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
def __enter__(self):
|
||||||
|
return self
|
||||||
|
|
||||||
|
def __exit__(self, type, value, traceback):
|
||||||
|
self.close()
|
||||||
|
|
||||||
def close(self):
|
def close(self):
|
||||||
self.sync()
|
self.sync()
|
||||||
try:
|
try:
|
||||||
|
@ -147,6 +153,7 @@ class Shelf(collections.MutableMapping):
|
||||||
def __del__(self):
|
def __del__(self):
|
||||||
if not hasattr(self, 'writeback'):
|
if not hasattr(self, 'writeback'):
|
||||||
# __init__ didn't succeed, so don't bother closing
|
# __init__ didn't succeed, so don't bother closing
|
||||||
|
# see http://bugs.python.org/issue1339007 for details
|
||||||
return
|
return
|
||||||
self.close()
|
self.close()
|
||||||
|
|
||||||
|
|
|
@ -148,6 +148,19 @@ class TestCase(unittest.TestCase):
|
||||||
p2 = d[encodedkey]
|
p2 = d[encodedkey]
|
||||||
self.assertNotEqual(p1, p2) # Write creates new object in store
|
self.assertNotEqual(p1, p2) # Write creates new object in store
|
||||||
|
|
||||||
|
def test_with(self):
|
||||||
|
d1 = {}
|
||||||
|
with shelve.Shelf(d1, protocol=2, writeback=False) as s:
|
||||||
|
s['key1'] = [1,2,3,4]
|
||||||
|
self.assertEqual(s['key1'], [1,2,3,4])
|
||||||
|
self.assertEqual(len(s), 1)
|
||||||
|
self.assertRaises(ValueError, len, s)
|
||||||
|
try:
|
||||||
|
s['key1']
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
self.fail('Closed shelf should not find a key')
|
||||||
|
|
||||||
from test import mapping_tests
|
from test import mapping_tests
|
||||||
|
|
||||||
|
|
|
@ -39,6 +39,9 @@ Core and Builtins
|
||||||
Library
|
Library
|
||||||
-------
|
-------
|
||||||
|
|
||||||
|
- Issue #13896: Make shelf instances work with 'with' as context managers.
|
||||||
|
Original patch by Filip Gruszczyński.
|
||||||
|
|
||||||
- Issue #15417: Add support for csh and fish in venv activation scripts.
|
- Issue #15417: Add support for csh and fish in venv activation scripts.
|
||||||
|
|
||||||
- Issue #16123: IDLE - deprecate running without a subprocess.
|
- Issue #16123: IDLE - deprecate running without a subprocess.
|
||||||
|
|
Loading…
Reference in New Issue