diff --git a/Lib/linecache.py b/Lib/linecache.py index 4b38a0464d8747..34f56d10b1d234 100644 --- a/Lib/linecache.py +++ b/Lib/linecache.py @@ -182,6 +182,10 @@ def lazycache(filename, module_globals): loader = getattr(spec, 'loader', None) if loader is None: loader = module_globals.get('__loader__') + mod_file = module_globals.get('__file__') + import importlib._bootstrap_external + if isinstance(loader, importlib._bootstrap_external.SourceFileLoader) and (not mod_file or (not mod_file.endswith(filename) and not mod_file.endswith('.pyc'))): + return False get_source = getattr(loader, 'get_source', None) if name and get_source: diff --git a/Lib/test/test_linecache.py b/Lib/test/test_linecache.py index 6f5955791407ea..4a38379a2f749a 100644 --- a/Lib/test/test_linecache.py +++ b/Lib/test/test_linecache.py @@ -206,8 +206,8 @@ def test_lazycache_smoke(self): lines = linecache.getlines(NONEXISTENT_FILENAME, globals()) linecache.clearcache() self.assertEqual( - True, linecache.lazycache(NONEXISTENT_FILENAME, globals())) - self.assertEqual(1, len(linecache.cache[NONEXISTENT_FILENAME])) + False, linecache.lazycache(NONEXISTENT_FILENAME, globals())) + self.assertEqual(False, NONEXISTENT_FILENAME in linecache.cache) # Note here that we're looking up a nonexistent filename with no # globals: this would error if the lazy value wasn't resolved. self.assertEqual(lines, linecache.getlines(NONEXISTENT_FILENAME)) @@ -232,11 +232,11 @@ def test_lazycache_bad_filename(self): def test_lazycache_already_cached(self): linecache.clearcache() - lines = linecache.getlines(NONEXISTENT_FILENAME, globals()) + lines = linecache.getlines(FILENAME, globals()) self.assertEqual( False, - linecache.lazycache(NONEXISTENT_FILENAME, globals())) - self.assertEqual(4, len(linecache.cache[NONEXISTENT_FILENAME])) + linecache.lazycache(FILENAME, globals())) + self.assertEqual(4, len(linecache.cache[FILENAME])) def test_memoryerror(self): lines = linecache.getlines(FILENAME) diff --git a/Misc/NEWS.d/next/Core and Builtins/2024-07-22-13-58-16.gh-issue-122071.c5EQZL.rst b/Misc/NEWS.d/next/Core and Builtins/2024-07-22-13-58-16.gh-issue-122071.c5EQZL.rst new file mode 100644 index 00000000000000..798777d33851ef --- /dev/null +++ b/Misc/NEWS.d/next/Core and Builtins/2024-07-22-13-58-16.gh-issue-122071.c5EQZL.rst @@ -0,0 +1 @@ +Fix global code leaks when reporting tracebacks in the REPL and :func:`exec`.