[Python-checkins] bpo-33587: inspect.getsource: reorder stat on file in linecache (GH-6805)

iritkatriel webhook-mailer at python.org
Fri Aug 26 10:21:25 EDT 2022


https://github.com/python/cpython/commit/c1581a928cc153076593c5c433a8dd36ce10fbfb
commit: c1581a928cc153076593c5c433a8dd36ce10fbfb
branch: main
author: Pankaj Pandey <pankaj86 at gmail.com>
committer: iritkatriel <1055913+iritkatriel at users.noreply.github.com>
date: 2022-08-26T15:20:48+01:00
summary:

bpo-33587: inspect.getsource: reorder stat on file in linecache (GH-6805)

* inspect.getsource: avoid stat on file in linecache

The check for os.path.exists() on source file is postponed in
inspect.getsourcefile() until needed avoiding an expensive filesystem
stat call and PEP 302 module loader check is moved last for performance
since it is an uncommon case.

files:
M Lib/inspect.py

diff --git a/Lib/inspect.py b/Lib/inspect.py
index cbc0632484b..498ee7ab9ea 100644
--- a/Lib/inspect.py
+++ b/Lib/inspect.py
@@ -946,6 +946,9 @@ def getsourcefile(object):
     elif any(filename.endswith(s) for s in
                  importlib.machinery.EXTENSION_SUFFIXES):
         return None
+    # return a filename found in the linecache even if it doesn't exist on disk
+    if filename in linecache.cache:
+        return filename
     if os.path.exists(filename):
         return filename
     # only return a non-existent filename if the module has a PEP 302 loader
@@ -954,9 +957,6 @@ def getsourcefile(object):
         return filename
     elif getattr(getattr(module, "__spec__", None), "loader", None) is not None:
         return filename
-    # or it is in the linecache
-    elif filename in linecache.cache:
-        return filename
 
 def getabsfile(object, _filename=None):
     """Return an absolute path to the source or compiled file for an object.



More information about the Python-checkins mailing list