On this page
  1. linecache
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Pulling a Context Window Around an Error Line
  7. Gotchas & Boundaries
  8. Common Functions

linecache

Prev: keyword | Up: stdlib_module | Next: locale
Rel: pathlib, os, io, time, fileinput
Ref: docs.python.org — linecache
Tags: #public #python3 #stdlib


Import

import linecache

Overview

In-memory line cache for Python source files (getline(), getlines(), checkcache(), clearcache()), used internally by traceback, pdb, and warnings to display source snippets quickly. Use linecache when building custom diagnostics, error reporters, or template debuggers that repeatedly look up specific line numbers.

Quick Start

import linecache

# Read line 1 of this module's own source file (1-indexed)
first_line = linecache.getline(linecache.__file__, 1)
assert isinstance(first_line, str) and len(first_line) > 0

Implementation Walkthrough

1. Pulling a Context Window Around an Error Line

getline(filename, lineno) safely returns "" (never raises IndexError or FileNotFoundError) when a file is missing or lineno is out of bounds:

import linecache

def source_excerpt(filename: str, lineno: int, radius: int = 2) -> list[tuple[int, str]]:
    start = max(1, lineno - radius)
    return [
        (n, line.rstrip("\n"))
        for n in range(start, lineno + radius + 1)
        if (line := linecache.getline(filename, n))
    ]

Gotchas & Boundaries

Common Functions

Linked from

Related notes