]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-45406: make inspect.getmodule() return None when getabsfile() raises FileNotFound...
authorIrit Katriel <1055913+iritkatriel@users.noreply.github.com>
Tue, 2 Nov 2021 21:55:51 +0000 (21:55 +0000)
committerGitHub <noreply@github.com>
Tue, 2 Nov 2021 21:55:51 +0000 (22:55 +0100)
Lib/inspect.py
Lib/test/test_inspect.py
Misc/NEWS.d/next/Library/2021-10-08-19-24-48.bpo-45406.Qh_Mz4.rst [new file with mode: 0644]

index 14a42fda56c65f3cd2cfcc20842c5ccd6a28168f..dd891112570c6a9eda1bdecfae9f836a51eb25cc 100644 (file)
@@ -858,7 +858,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])
index 7479eb326e6f5c875f865179b5ec10176ca11c1f..d43486a219158be1bc0ebc52f8483e26ee6c752c 100644 (file)
@@ -493,6 +493,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 (file)
index 0000000..2c3a816
--- /dev/null
@@ -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