Skip to content

Commit cfdd7d2

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 8af3090 commit cfdd7d2

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
@@ -859,7 +859,7 @@ def getmodule(object, _filename=None):
859859
# Try the cache again with the absolute file name
860860
try:
861861
file = getabsfile(object, _filename)
862-
except TypeError:
862+
except (TypeError, FileNotFoundError):
863863
return None
864864
if file in modulesbyfile:
865865
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)