Skip to content

Commit d407d2a

Browse files
flying-sheepmiss-islington
authored andcommitted
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
1 parent 65e5860 commit d407d2a

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
@@ -659,9 +659,9 @@ def getfile(object):
659659
raise TypeError('{!r} is a built-in module'.format(object))
660660
if isclass(object):
661661
if hasattr(object, '__module__'):
662-
object = sys.modules.get(object.__module__)
663-
if getattr(object, '__file__', None):
664-
return object.__file__
662+
module = sys.modules.get(object.__module__)
663+
if getattr(module, '__file__', None):
664+
return module.__file__
665665
raise TypeError('{!r} is a built-in class'.format(object))
666666
if ismethod(object):
667667
object = object.__func__

Lib/test/test_inspect.py

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

516+
def test_getfile_builtin_module(self):
517+
with self.assertRaises(TypeError) as e:
518+
inspect.getfile(sys)
519+
self.assertTrue(str(e.exception).startswith('<module'))
520+
521+
def test_getfile_builtin_class(self):
522+
with self.assertRaises(TypeError) as e:
523+
inspect.getfile(int)
524+
self.assertTrue(str(e.exception).startswith('<class'))
525+
526+
def test_getfile_builtin_function_or_method(self):
527+
with self.assertRaises(TypeError) as e_abs:
528+
inspect.getfile(abs)
529+
self.assertIn('expected, got', str(e_abs.exception))
530+
with self.assertRaises(TypeError) as e_append:
531+
inspect.getfile(list.append)
532+
self.assertIn('expected, got', str(e_append.exception))
533+
516534
def test_getfile_class_without_module(self):
517535
class CM(type):
518536
@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)