From df719fda31afa5058b44d6517f50003cbc42dc90 Mon Sep 17 00:00:00 2001 From: Victor Stinner Date: Thu, 9 Nov 2023 15:03:10 +0100 Subject: [PATCH] gh-111881: Import lazily linecache in traceback The linecache module is only used by StackSummary and FrameSummary.line property. Import the linecache module lazily to speedup Python imports and reduce the number of imports when the traceback module is imported. --- Lib/traceback.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Lib/traceback.py b/Lib/traceback.py index b25a7291f6be51..2f7d5d3d511820 100644 --- a/Lib/traceback.py +++ b/Lib/traceback.py @@ -2,7 +2,6 @@ import collections.abc import itertools -import linecache import sys import textwrap from contextlib import suppress @@ -333,6 +332,7 @@ def line(self): if self._line is None: if self.lineno is None: return None + import linecache self._line = linecache.getline(self.filename, self.lineno) return self._line.strip() @@ -430,6 +430,8 @@ def _extract_from_extended_frame_gen(klass, frame_gen, *, limit=None, else: frame_gen = collections.deque(frame_gen, maxlen=-limit) + import linecache + result = klass() fnames = set() for f, (lineno, end_lineno, colno, end_colno) in frame_gen: