linecache retrieves a particular line without making every caller manage repeated file reads. It supports parts of traceback and tools that display source-code context.

Retrieve a particular line

import linecache
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as folder:
    path = Path(folder, "sample.py")
    path.write_text("first = 1\nsecond = 2\n", encoding="utf-8")
    assert linecache.getline(str(path), 2) == "second = 2\n"
    linecache.clearcache()

Understand silent failures

getline() returns an empty string for a missing line or many read failures rather than exposing those exceptions. If an application must distinguish a missing file from an invalid line, validate the path and range separately.

Refresh after file changes

Call checkcache(filename) when another process or part of the program may modify a file. clearcache() drops every entry. Do not use this module as general storage or assume freshness without an invalidation policy.

Keep learning

Continue with debugging Python with PDB. The official Python documentation, accessed July 22, 2026, covers getline, invalidation, and module-loader support.