From b64a5316b8b8c4919d0bbb83942632e498e3a74a Mon Sep 17 00:00:00 2001 From: Victor Stinner Date: Thu, 9 Nov 2023 15:15:43 +0100 Subject: [PATCH] gh-111881: Use lazy import in doctest Use lazy import for difflib and linecache imports in doctest to speedup Python startup and reduce the number of imports when running tests. --- Lib/doctest.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/Lib/doctest.py b/Lib/doctest.py index 2f14aa08334895..fb469c2a242261 100644 --- a/Lib/doctest.py +++ b/Lib/doctest.py @@ -93,9 +93,7 @@ def _test(): ] import __future__ -import difflib import inspect -import linecache import os import pdb import re @@ -932,6 +930,8 @@ def find(self, obj, name=None, module=None, globs=None, extraglobs=None): if file is None: source_lines = None else: + import linecache + if module is not None: # Supply the module globals in case the module was # originally loaded via a PEP 302 loader and @@ -1528,6 +1528,8 @@ def out(s): self.debugger.reset() pdb.set_trace = self.debugger.set_trace + import linecache + # Patch linecache.getlines, so we can see the example's source # when we're inside the debugger. self.save_linecache_getlines = linecache.getlines @@ -1738,6 +1740,8 @@ def output_difference(self, example, got, optionflags): # Check if we should use diff. if self._do_a_fancy_diff(want, got, optionflags): + import difflib + # Split want & got into lines. want_lines = want.splitlines(keepends=True) got_lines = got.splitlines(keepends=True)