From 511865da78c58e58eca9104d661fd8f3affeff28 Mon Sep 17 00:00:00 2001 From: Irit Katriel Date: Fri, 8 Oct 2021 19:54:38 +0100 Subject: [PATCH 1/3] bpo-45406: make inspect.getmodule() return None when getabsfile() raises FileNotFoundError --- Lib/inspect.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Lib/inspect.py b/Lib/inspect.py index 1b2fc918c81313..65646da9948b40 100644 --- a/Lib/inspect.py +++ b/Lib/inspect.py @@ -859,7 +859,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]) From 2edfc765d9eee12ce9c1d5855655ffef4b7a5726 Mon Sep 17 00:00:00 2001 From: Irit Katriel Date: Fri, 8 Oct 2021 20:17:32 +0100 Subject: [PATCH 2/3] add test --- Lib/test/test_inspect.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Lib/test/test_inspect.py b/Lib/test/test_inspect.py index 0e9191e5073cc6..ff14bc7cdb98e1 100644 --- a/Lib/test/test_inspect.py +++ b/Lib/test/test_inspect.py @@ -493,6 +493,15 @@ def test_getmodule(self): # 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") From 34b13d460276834ecdb4e0cfea9b956c0d844cf9 Mon Sep 17 00:00:00 2001 From: "blurb-it[bot]" <43283697+blurb-it[bot]@users.noreply.github.com> Date: Fri, 8 Oct 2021 19:24:50 +0000 Subject: [PATCH 3/3] =?UTF-8?q?=F0=9F=93=9C=F0=9F=A4=96=20Added=20by=20blu?= =?UTF-8?q?rb=5Fit.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../NEWS.d/next/Library/2021-10-08-19-24-48.bpo-45406.Qh_Mz4.rst | 1 + 1 file changed, 1 insertion(+) create mode 100644 Misc/NEWS.d/next/Library/2021-10-08-19-24-48.bpo-45406.Qh_Mz4.rst 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 00000000000000..2c3a8165aeb492 --- /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