Skip to content

bpo-45406: make inspect.getmodule() return None when getabsfile() rai… #28824

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Nov 2, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Lib/inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -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])
Expand Down
9 changes: 9 additions & 0 deletions Lib/test/test_inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
Original file line number Diff line number Diff line change
@@ -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.