Skip to content

Commit c1581a9

Browse files
authored
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.
1 parent 771eff2 commit c1581a9

File tree

1 file changed

+3
-3
lines changed

1 file changed

+3
-3
lines changed

Lib/inspect.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -946,6 +946,9 @@ def getsourcefile(object):
946946
elif any(filename.endswith(s) for s in
947947
importlib.machinery.EXTENSION_SUFFIXES):
948948
return None
949+
# return a filename found in the linecache even if it doesn't exist on disk
950+
if filename in linecache.cache:
951+
return filename
949952
if os.path.exists(filename):
950953
return filename
951954
# only return a non-existent filename if the module has a PEP 302 loader
@@ -954,9 +957,6 @@ def getsourcefile(object):
954957
return filename
955958
elif getattr(getattr(module, "__spec__", None), "loader", None) is not None:
956959
return filename
957-
# or it is in the linecache
958-
elif filename in linecache.cache:
959-
return filename
960960

961961
def getabsfile(object, _filename=None):
962962
"""Return an absolute path to the source or compiled file for an object.

0 commit comments

Comments
 (0)