Skip to content

Commit 5f527ca

Browse files
bpo-45406: make inspect.getmodule() return None when getabsfile() raises FileNotFoundError (GH-28824)
(cherry picked from commit a459a81) Co-authored-by: Irit Katriel <[email protected]>
1 parent d3e7755 commit 5f527ca

File tree

3 files changed

+11
-1
lines changed

3 files changed

+11
-1
lines changed

Lib/inspect.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -736,7 +736,7 @@ def getmodule(object, _filename=None):
736736
# Try the cache again with the absolute file name
737737
try:
738738
file = getabsfile(object, _filename)
739-
except TypeError:
739+
except (TypeError, FileNotFoundError):
740740
return None
741741
if file in modulesbyfile:
742742
return sys.modules.get(modulesbyfile[file])

Lib/test/test_inspect.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -488,6 +488,15 @@ def test_getmodule(self):
488488
# Check filename override
489489
self.assertEqual(inspect.getmodule(None, modfile), mod)
490490

491+
def test_getmodule_file_not_found(self):
492+
# See bpo-45406
493+
def _getabsfile(obj, _filename):
494+
raise FileNotFoundError('bad file')
495+
with unittest.mock.patch('inspect.getabsfile', _getabsfile):
496+
f = inspect.currentframe()
497+
self.assertIsNone(inspect.getmodule(f))
498+
inspect.getouterframes(f) # smoke test
499+
491500
def test_getframeinfo_get_first_line(self):
492501
frame_info = inspect.getframeinfo(self.fodderModule.fr, 50)
493502
self.assertEqual(frame_info.code_context[0], "# line 1\n")
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Make :func:`inspect.getmodule` catch ``FileNotFoundError`` raised by :'func:`inspect.getabsfile`, and return ``None`` to indicate that the module could not be determined.

0 commit comments

Comments
 (0)