Python Basics: Retrieve Source Lines and Refresh Cached Text
Diagnostic tools often need one source line by number. linecache offers one-based lookup, but a cached result needs deliberate refresh when the underlying source changes.
Prepare a scratch directory
Tested on Linux with CPython 3.12.14. You need Bash, a text editor, the named runtime, and standard mktemp, rm, and rmdir utilities. Run Python without -O so assertions remain enabled. The examples use only controlled local data; generated fixture directories are cleaned automatically.
Keep the same terminal open. Stop if setup fails, before saving the source:
start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1Run the example
Save this as demonstrate-linecache.py:
import linecache
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as directory:
path = Path(directory) / "sample.py"
path.write_text("name = 'demo'\ncount = 2\n", encoding="utf-8")
filename = str(path)
print("Line 2:", linecache.getline(filename, 2).strip())
print("Missing line:", repr(linecache.getline(filename, 20)))
path.write_text("name = 'demo'\ncount = 2000\n", encoding="utf-8")
print("Cached:", linecache.getline(filename, 2).strip())
linecache.checkcache(filename)
current = linecache.getline(filename, 2)
assert current == "count = 2000\n"
print("Refreshed:", current.strip())
linecache.clearcache()Run it:
python3 -B demonstrate-linecache.pyObserved output:
Line 2: count = 2
Missing line: ''
Cached: count = 2
Refreshed: count = 2000Read the result
The first lookup populates the cache. A missing line returns an empty string. The next lookup still sees the earlier cached text until checkcache detects the changed file size and invalidates its entry.
Apply it carefully
An empty result can indicate an unavailable file as well as an out-of-range line. checkcache relies on metadata; a rewrite preserving size and timestamp may require clearcache. This is useful for source diagnostics, not a substitute for explicit file I/O when errors must be reported.
The official reference describes the behavior and options. These checks cover the fixture above rather than every input or platform.
Clean up
Remove the saved source, return to the starting directory, then remove the empty practice directory:
rm -- demonstrate-linecache.py
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dirIf the directory is not empty, inspect its remaining contents rather than deleting unknown files.
Acknowledgements
This post was created with assistance from AI.