From f10548f1d4f0fd1b86b88df6500b361b22530ee0 Mon Sep 17 00:00:00 2001 From: Pablo Galindo Date: Wed, 3 Apr 2024 12:16:52 +0100 Subject: [PATCH 1/2] gh-67224: Make linecache imports relative to improve startup speed Signed-off-by: Pablo Galindo --- Lib/linecache.py | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/Lib/linecache.py b/Lib/linecache.py index b97999fc1dc909..5f8d3b315d1bea 100644 --- a/Lib/linecache.py +++ b/Lib/linecache.py @@ -5,9 +5,6 @@ that name. """ -import sys -import os - __all__ = ["getline", "clearcache", "checkcache", "lazycache"] @@ -67,15 +64,25 @@ def checkcache(filename=None): if mtime is None: continue # no-op for files loaded via a __loader__ try: + # This import can fail if the interpreter is shutting down + import os stat = os.stat(fullname) except OSError: cache.pop(filename, None) continue + except ImportError: + return if size != stat.st_size or mtime != stat.st_mtime: cache.pop(filename, None) def updatecache(filename, module_globals=None): + # These imports are not at top level because linecache is in the critical + # path of the interpreter startup and importing os and sys take a lot of time + # and slow down the startup sequence. + import os + import sys + """Update a cache entry and return its list of lines. If something's wrong, print a message, discard the cache entry, and return an empty list.""" From 9ab361adc29cdcdc4834b654549178535e5c9f08 Mon Sep 17 00:00:00 2001 From: Pablo Galindo Salgado Date: Wed, 10 Apr 2024 18:32:42 +0100 Subject: [PATCH 2/2] Update Lib/linecache.py --- Lib/linecache.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Lib/linecache.py b/Lib/linecache.py index 5f8d3b315d1bea..d1113b108dc5e4 100644 --- a/Lib/linecache.py +++ b/Lib/linecache.py @@ -66,12 +66,13 @@ def checkcache(filename=None): try: # This import can fail if the interpreter is shutting down import os + except ImportError: + return + try: stat = os.stat(fullname) except OSError: cache.pop(filename, None) continue - except ImportError: - return if size != stat.st_size or mtime != stat.st_mtime: cache.pop(filename, None)