Skip to content

Commit a459a81

Browse files
authored
bpo-45406: make inspect.getmodule() return None when getabsfile() raises FileNotFoundError (GH-28824)
1 parent 48824fa commit a459a81

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
@@ -858,7 +858,7 @@ def getmodule(object, _filename=None):
858858
# Try the cache again with the absolute file name
859859
try:
860860
file = getabsfile(object, _filename)
861-
except TypeError:
861+
except (TypeError, FileNotFoundError):
862862
return None
863863
if file in modulesbyfile:
864864
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
@@ -493,6 +493,15 @@ def test_getmodule(self):
493493
# Check filename override
494494
self.assertEqual(inspect.getmodule(None, modfile), mod)
495495

496+
def test_getmodule_file_not_found(self):
497+
# See bpo-45406
498+
def _getabsfile(obj, _filename):
499+
raise FileNotFoundError('bad file')
500+
with unittest.mock.patch('inspect.getabsfile', _getabsfile):
501+
f = inspect.currentframe()
502+
self.assertIsNone(inspect.getmodule(f))
503+
inspect.getouterframes(f) # smoke test
504+
496505
def test_getframeinfo_get_first_line(self):
497506
frame_info = inspect.getframeinfo(self.fodderModule.fr, 50)
498507
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)