From c512adc90d49b1dae3ae14c81826e03c9ea46ba5 Mon Sep 17 00:00:00 2001 From: Serhiy Storchaka Date: Wed, 1 Apr 2015 16:54:05 +0300 Subject: [PATCH] Issue #23838: linecache now clears the cache and returns an empty result on MemoryError. --- Lib/linecache.py | 6 +++++- Lib/test/test_linecache.py | 19 ++++++++++++++++--- Misc/NEWS | 3 +++ 3 files changed, 24 insertions(+), 4 deletions(-) diff --git a/Lib/linecache.py b/Lib/linecache.py index e505b031240..884cbf493a4 100644 --- a/Lib/linecache.py +++ b/Lib/linecache.py @@ -37,8 +37,12 @@ def getlines(filename, module_globals=None): if filename in cache: return cache[filename][2] - else: + + 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 index 5fe0554572c..79157de43f6 100644 --- a/Lib/test/test_linecache.py +++ b/Lib/test/test_linecache.py @@ -126,8 +126,21 @@ class LineCacheTests(unittest.TestCase): self.assertEqual(line, getline(source_name, index + 1)) source_list.append(line) -def test_main(): - support.run_unittest(LineCacheTests) + 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) + + 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 index 33fc0ee3b02..58cdebdee26 100644 --- a/Misc/NEWS +++ b/Misc/NEWS @@ -21,6 +21,9 @@ Core and Builtins Library ------- +- Issue #23838: linecache now clears the cache and returns an empty result on + MemoryError. + - Issue #18473: Fixed 2to3 and 3to2 compatible pickle mappings. Fixed ambigious reverse mappings. Added many new mappings. Import mapping is no longer applied to modules already mapped with full name mapping.