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
This commit is contained in:
Philipp A 2019-06-08 14:05:46 +02:00 committed by Miss Islington (bot)
parent 65e5860fcc
commit d407d2a726
3 changed files with 22 additions and 3 deletions

View File

@ -659,9 +659,9 @@ def getfile(object):
raise TypeError('{!r} is a built-in module'.format(object)) raise TypeError('{!r} is a built-in module'.format(object))
if isclass(object): if isclass(object):
if hasattr(object, '__module__'): if hasattr(object, '__module__'):
object = sys.modules.get(object.__module__) module = sys.modules.get(object.__module__)
if getattr(object, '__file__', None): if getattr(module, '__file__', None):
return object.__file__ return module.__file__
raise TypeError('{!r} is a built-in class'.format(object)) raise TypeError('{!r} is a built-in class'.format(object))
if ismethod(object): if ismethod(object):
object = object.__func__ object = object.__func__

View File

@ -513,6 +513,24 @@ class TestRetrievingSourceCode(GetSourceBase):
def test_getfile(self): def test_getfile(self):
self.assertEqual(inspect.getfile(mod.StupidGit), mod.__file__) self.assertEqual(inspect.getfile(mod.StupidGit), mod.__file__)
def test_getfile_builtin_module(self):
with self.assertRaises(TypeError) as e:
inspect.getfile(sys)
self.assertTrue(str(e.exception).startswith('<module'))
def test_getfile_builtin_class(self):
with self.assertRaises(TypeError) as e:
inspect.getfile(int)
self.assertTrue(str(e.exception).startswith('<class'))
def test_getfile_builtin_function_or_method(self):
with self.assertRaises(TypeError) as e_abs:
inspect.getfile(abs)
self.assertIn('expected, got', str(e_abs.exception))
with self.assertRaises(TypeError) as e_append:
inspect.getfile(list.append)
self.assertIn('expected, got', str(e_append.exception))
def test_getfile_class_without_module(self): def test_getfile_class_without_module(self):
class CM(type): class CM(type):
@property @property

View File

@ -0,0 +1 @@
The exception message for ``inspect.getfile()`` now correctly reports the passed class rather than the builtins module.