bpo-45406: make inspect.getmodule() return None when getabsfile() raises FileNotFoundError (GH-28824)

(cherry picked from commit a459a81530)

Co-authored-by: Irit Katriel <1055913+iritkatriel@users.noreply.github.com>
This commit is contained in:
Miss Islington (bot) 2021-11-02 15:23:43 -07:00 committed by GitHub
parent 8af3090cb7
commit cfdd7d26a7
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 11 additions and 1 deletions

View file

@ -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])

View file

@ -493,6 +493,15 @@ class TestRetrievingSourceCode(GetSourceBase):
# 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")

View file

@ -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.