Skip to content

Commit 51c9cc7

Browse files
bpo-37173: Show passed class in inspect.getfile error (GH-13861)
Currently, inspect.getfile(str) will report nonsense: ```pytb >>> inspect.getfile(str) TypeError: <module 'builtins' (built-in)> is a built-in class ``` This fixes that https://bugs.python.org/issue37173 (cherry picked from commit d407d2a) Co-authored-by: Philipp A <[email protected]>
1 parent 10b4fd9 commit 51c9cc7

File tree

3 files changed

+22
-3
lines changed

3 files changed

+22
-3
lines changed

Lib/inspect.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -647,9 +647,9 @@ def getfile(object):
647647
raise TypeError('{!r} is a built-in module'.format(object))
648648
if isclass(object):
649649
if hasattr(object, '__module__'):
650-
object = sys.modules.get(object.__module__)
651-
if getattr(object, '__file__', None):
652-
return object.__file__
650+
module = sys.modules.get(object.__module__)
651+
if getattr(module, '__file__', None):
652+
return module.__file__
653653
raise TypeError('{!r} is a built-in class'.format(object))
654654
if ismethod(object):
655655
object = object.__func__

Lib/test/test_inspect.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -478,6 +478,24 @@ def test_getsourcefile(self):
478478
def test_getfile(self):
479479
self.assertEqual(inspect.getfile(mod.StupidGit), mod.__file__)
480480

481+
def test_getfile_builtin_module(self):
482+
with self.assertRaises(TypeError) as e:
483+
inspect.getfile(sys)
484+
self.assertTrue(str(e.exception).startswith('<module'))
485+
486+
def test_getfile_builtin_class(self):
487+
with self.assertRaises(TypeError) as e:
488+
inspect.getfile(int)
489+
self.assertTrue(str(e.exception).startswith('<class'))
490+
491+
def test_getfile_builtin_function_or_method(self):
492+
with self.assertRaises(TypeError) as e_abs:
493+
inspect.getfile(abs)
494+
self.assertIn('expected, got', str(e_abs.exception))
495+
with self.assertRaises(TypeError) as e_append:
496+
inspect.getfile(list.append)
497+
self.assertIn('expected, got', str(e_append.exception))
498+
481499
def test_getfile_class_without_module(self):
482500
class CM(type):
483501
@property
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
The exception message for ``inspect.getfile()`` now correctly reports the passed class rather than the builtins module.

0 commit comments

Comments
 (0)