summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>2021-11-02 22:26:40 (GMT)
committerGitHub <noreply@github.com>2021-11-02 22:26:40 (GMT)
commit5f527caf15c52acc3f6e865721cdf781209f11ca (patch)
tree0b12c7b50addcb18bb7da51e315a344f77c0cbc3
parentd3e775501566138347ca9d10ce57afdc1fcd3859 (diff)
downloadcpython-5f527caf15c52acc3f6e865721cdf781209f11ca.zip
cpython-5f527caf15c52acc3f6e865721cdf781209f11ca.tar.gz
cpython-5f527caf15c52acc3f6e865721cdf781209f11ca.tar.bz2
bpo-45406: make inspect.getmodule() return None when getabsfile() raises FileNotFoundError (GH-28824)
(cherry picked from commit a459a81530de700b3d3faeb827b22ed1c9985812) Co-authored-by: Irit Katriel <1055913+iritkatriel@users.noreply.github.com>
-rw-r--r--Lib/inspect.py2
-rw-r--r--Lib/test/test_inspect.py9
-rw-r--r--Misc/NEWS.d/next/Library/2021-10-08-19-24-48.bpo-45406.Qh_Mz4.rst1
3 files changed, 11 insertions, 1 deletions
diff --git a/Lib/inspect.py b/Lib/inspect.py
index 64605c3..10b5d14 100644
--- a/Lib/inspect.py
+++ b/Lib/inspect.py
@@ -736,7 +736,7 @@ def getmodule(object, _filename=None):
# Try the cache again with the absolute file name
try:
file = getabsfile(object, _filename)
- except TypeError:
+ except (TypeError, FileNotFoundError):
return None
if file in modulesbyfile:
return sys.modules.get(modulesbyfile[file])
diff --git a/Lib/test/test_inspect.py b/Lib/test/test_inspect.py
index 8a8844e..08aed24 100644
--- a/Lib/test/test_inspect.py
+++ b/Lib/test/test_inspect.py
@@ -488,6 +488,15 @@ class TestRetrievingSourceCode(GetSourceBase):
# Check filename override
self.assertEqual(inspect.getmodule(None, modfile), mod)
+ def test_getmodule_file_not_found(self):
+ # See bpo-45406
+ def _getabsfile(obj, _filename):
+ raise FileNotFoundError('bad file')
+ with unittest.mock.patch('inspect.getabsfile', _getabsfile):
+ f = inspect.currentframe()
+ self.assertIsNone(inspect.getmodule(f))
+ inspect.getouterframes(f) # smoke test
+
def test_getframeinfo_get_first_line(self):
frame_info = inspect.getframeinfo(self.fodderModule.fr, 50)
self.assertEqual(frame_info.code_context[0], "# line 1\n")
diff --git a/Misc/NEWS.d/next/Library/2021-10-08-19-24-48.bpo-45406.Qh_Mz4.rst b/Misc/NEWS.d/next/Library/2021-10-08-19-24-48.bpo-45406.Qh_Mz4.rst
new file mode 100644
index 0000000..2c3a816
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2021-10-08-19-24-48.bpo-45406.Qh_Mz4.rst
@@ -0,0 +1 @@
+Make :func:`inspect.getmodule` catch ``FileNotFoundError`` raised by :'func:`inspect.getabsfile`, and return ``None`` to indicate that the module could not be determined. \ No newline at end of file