[Python-checkins] cpython: Issue #13896: Make shelf instances work with 'with' as context managers.
andrew.svetlov
python-checkins at python.org
Sat Oct 6 12:52:38 CEST 2012
http://hg.python.org/cpython/rev/3c1df1ede882
changeset: 79507:3c1df1ede882
user: Andrew Svetlov <andrew.svetlov at gmail.com>
date: Sat Oct 06 13:52:19 2012 +0300
summary:
Issue #13896: Make shelf instances work with 'with' as context managers.
Original patch by Filip Gruszczyński.
files:
Lib/shelve.py | 7 +++++++
Lib/test/test_shelve.py | 13 +++++++++++++
Misc/NEWS | 3 +++
3 files changed, 23 insertions(+), 0 deletions(-)
diff --git a/Lib/shelve.py b/Lib/shelve.py
--- a/Lib/shelve.py
+++ b/Lib/shelve.py
@@ -131,6 +131,12 @@
except KeyError:
pass
+ def __enter__(self):
+ return self
+
+ def __exit__(self, type, value, traceback):
+ self.close()
+
def close(self):
self.sync()
try:
@@ -147,6 +153,7 @@
def __del__(self):
if not hasattr(self, 'writeback'):
# __init__ didn't succeed, so don't bother closing
+ # see http://bugs.python.org/issue1339007 for details
return
self.close()
diff --git a/Lib/test/test_shelve.py b/Lib/test/test_shelve.py
--- a/Lib/test/test_shelve.py
+++ b/Lib/test/test_shelve.py
@@ -148,6 +148,19 @@
p2 = d[encodedkey]
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
diff --git a/Misc/NEWS b/Misc/NEWS
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -39,6 +39,9 @@
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 #16123: IDLE - deprecate running without a subprocess.
--
Repository URL: http://hg.python.org/cpython
More information about the Python-checkins
mailing list