From 7d823c16cec23dd757e0481e2c4e0d3e36bfac7b Mon Sep 17 00:00:00 2001 From: Pankaj Pandey Date: Thu, 10 May 2018 17:56:59 +0530 Subject: [PATCH 1/2] 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. --- Lib/inspect.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Lib/inspect.py b/Lib/inspect.py index 512785f9237ea2..095b100ea49a56 100644 --- a/Lib/inspect.py +++ b/Lib/inspect.py @@ -690,14 +690,14 @@ def getsourcefile(object): elif any(filename.endswith(s) for s in importlib.machinery.EXTENSION_SUFFIXES): return None + # return a non-existent filename if it is in the linecache + 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 + # or if the module has a PEP 302 loader (uncommon case being checked last) if getattr(getmodule(object, filename), '__loader__', None) is not None: return filename - # or it is in the linecache - if filename in linecache.cache: - return filename def getabsfile(object, _filename=None): """Return an absolute path to the source or compiled file for an object. From af56911e9847e3c7fdc869a1642f0af54242e0ae Mon Sep 17 00:00:00 2001 From: Tal Einat Date: Sat, 19 Sep 2020 23:14:15 +0300 Subject: [PATCH 2/2] tweak code comment --- Lib/inspect.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Lib/inspect.py b/Lib/inspect.py index 095b100ea49a56..7102c75780c7b9 100644 --- a/Lib/inspect.py +++ b/Lib/inspect.py @@ -690,12 +690,12 @@ def getsourcefile(object): elif any(filename.endswith(s) for s in importlib.machinery.EXTENSION_SUFFIXES): return None - # return a non-existent filename if it is in the linecache + # 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 - # or if the module has a PEP 302 loader (uncommon case being checked last) + # return a non-existent filename if the module has a PEP 302 loader if getattr(getmodule(object, filename), '__loader__', None) is not None: return filename