Skip to content

Commit 4515a59

Browse files
ganziqimcsabella
authored andcommitted
Fix linecache.py add lazycache to __all__ and use dict.clear to clear the cache (GH-4641)
1 parent 8271441 commit 4515a59

File tree

2 files changed

+21
-18
lines changed

2 files changed

+21
-18
lines changed

Lib/linecache.py

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -10,17 +10,8 @@
1010
import os
1111
import tokenize
1212

13-
__all__ = ["getline", "clearcache", "checkcache"]
13+
__all__ = ["getline", "clearcache", "checkcache", "lazycache"]
1414

15-
def getline(filename, lineno, module_globals=None):
16-
lines = getlines(filename, module_globals)
17-
if 1 <= lineno <= len(lines):
18-
return lines[lineno-1]
19-
else:
20-
return ''
21-
22-
23-
# The cache
2415

2516
# The cache. Maps filenames to either a thunk which will provide source code,
2617
# or a tuple (size, mtime, lines, fullname) once loaded.
@@ -29,9 +20,17 @@ def getline(filename, lineno, module_globals=None):
2920

3021
def clearcache():
3122
"""Clear the cache entirely."""
23+
cache.clear()
3224

33-
global cache
34-
cache = {}
25+
26+
def getline(filename, lineno, module_globals=None):
27+
"""Get a line for a Python source file from the cache.
28+
Update the cache if it doesn't contain an entry for this file already."""
29+
30+
lines = getlines(filename, module_globals)
31+
if 1 <= lineno <= len(lines):
32+
return lines[lineno - 1]
33+
return ''
3534

3635

3736
def getlines(filename, module_globals=None):
@@ -56,11 +55,10 @@ def checkcache(filename=None):
5655

5756
if filename is None:
5857
filenames = list(cache.keys())
58+
elif filename in cache:
59+
filenames = [filename]
5960
else:
60-
if filename in cache:
61-
filenames = [filename]
62-
else:
63-
return
61+
return
6462

6563
for filename in filenames:
6664
entry = cache[filename]
@@ -109,8 +107,10 @@ def updatecache(filename, module_globals=None):
109107
# for this module.
110108
return []
111109
cache[filename] = (
112-
len(data), None,
113-
[line+'\n' for line in data.splitlines()], fullname
110+
len(data),
111+
None,
112+
[line + '\n' for line in data.splitlines()],
113+
fullname
114114
)
115115
return cache[filename][2]
116116

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
* Add `lazycache` function to `__all__`.
2+
* Use `dict.clear` to clear the cache.
3+
* Refactoring `getline` function and `checkcache` function.

0 commit comments

Comments
 (0)