Skip to content

bpo-37173: Show passed class in inspect.getfile error #13861

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
Jun 8, 2019
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
6 changes: 3 additions & 3 deletions Lib/inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -659,9 +659,9 @@ def getfile(object):
raise TypeError('{!r} is a built-in module'.format(object))
if isclass(object):
if hasattr(object, '__module__'):
object = sys.modules.get(object.__module__)
if getattr(object, '__file__', None):
return object.__file__
module = sys.modules.get(object.__module__)
if getattr(module, '__file__', None):
return module.__file__
raise TypeError('{!r} is a built-in class'.format(object))
if ismethod(object):
object = object.__func__
Expand Down
18 changes: 18 additions & 0 deletions Lib/test/test_inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -513,6 +513,24 @@ def test_getsourcefile(self):
def test_getfile(self):
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):
class CM(type):
@property
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
The exception message for ``inspect.getfile()`` now correctly reports the passed class rather than the builtins module.