[Python-checkins] cpython (merge 3.4 -> default): Issue #23838: linecache now clears the cache and returns an empty result on

serhiy.storchaka python-checkins at python.org
Wed Apr 1 15:59:07 CEST 2015


https://hg.python.org/cpython/rev/ab2326c801c2
changeset:   95346:ab2326c801c2
parent:      95343:f4acf2a31151
parent:      95345:88a0e6cd93c3
user:        Serhiy Storchaka <storchaka at gmail.com>
date:        Wed Apr 01 16:56:13 2015 +0300
summary:
  Issue #23838: linecache now clears the cache and returns an empty result on
MemoryError.

files:
  Lib/linecache.py           |  11 +++++++----
  Lib/test/test_linecache.py |  18 +++++++++++++++---
  Misc/NEWS                  |   3 +++
  3 files changed, 25 insertions(+), 7 deletions(-)


diff --git a/Lib/linecache.py b/Lib/linecache.py
--- a/Lib/linecache.py
+++ b/Lib/linecache.py
@@ -40,11 +40,14 @@
 
     if filename in cache:
         entry = cache[filename]
-        if len(entry) == 1:
-            return updatecache(filename, module_globals)
-        return cache[filename][2]
-    else:
+        if len(entry) != 1:
+            return cache[filename][2]
+
+    try:
         return updatecache(filename, module_globals)
+    except MemoryError:
+        clearcache()
+        return []
 
 
 def checkcache(filename=None):
diff --git a/Lib/test/test_linecache.py b/Lib/test/test_linecache.py
--- a/Lib/test/test_linecache.py
+++ b/Lib/test/test_linecache.py
@@ -169,9 +169,21 @@
             linecache.lazycache(NONEXISTENT_FILENAME, globals()))
         self.assertEqual(4, len(linecache.cache[NONEXISTENT_FILENAME]))
 
+    def test_memoryerror(self):
+        lines = linecache.getlines(FILENAME)
+        self.assertTrue(lines)
+        def raise_memoryerror(*args, **kwargs):
+            raise MemoryError
+        with support.swap_attr(linecache, 'updatecache', raise_memoryerror):
+            lines2 = linecache.getlines(FILENAME)
+        self.assertEqual(lines2, lines)
 
-def test_main():
-    support.run_unittest(LineCacheTests)
+        linecache.clearcache()
+        with support.swap_attr(linecache, 'updatecache', raise_memoryerror):
+            lines3 = linecache.getlines(FILENAME)
+        self.assertEqual(lines3, [])
+        self.assertEqual(linecache.getlines(FILENAME), lines)
+
 
 if __name__ == "__main__":
-    test_main()
+    unittest.main()
diff --git a/Misc/NEWS b/Misc/NEWS
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -13,6 +13,9 @@
 Library
 -------
 
+- Issue #23838: linecache now clears the cache and returns an empty result on
+  MemoryError.
+
 - Issue #10395: Added os.path.commonpath(). Implemented in posixpath and ntpath.
   Based on patch by Rafik Draoui.
 

-- 
Repository URL: https://hg.python.org/cpython


More information about the Python-checkins mailing list