Skip to content
Open
Show file tree
Hide file tree
Changes from 5 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
4 changes: 3 additions & 1 deletion Lib/inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -819,7 +819,9 @@ def getfile(object):
if ismodule(object):
if getattr(object, '__file__', None):
return object.__file__
raise TypeError('{!r} is a built-in module'.format(object))
if getattr(object, '__spec__', None) is not None:
raise TypeError(f'{object!r} is a built-in module')
raise TypeError(f'Cannot get source from {object!r}')
if isclass(object):
if hasattr(object, '__module__'):
module = sys.modules.get(object.__module__)
Expand Down
9 changes: 9 additions & 0 deletions Lib/test/test_inspect/test_inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -811,6 +811,15 @@ def test_getfile_builtin_module(self):
inspect.getfile(sys)
self.assertStartsWith(str(e.exception), '<module')

def test_getfile_custom_module(self):
import re
custom_module = types.ModuleType('custom_module')
msg = re.escape(
f'Cannot get source from {custom_module!r}'
)
with self.assertRaisesRegex(TypeError, msg) as e:
inspect.getfile(custom_module)

def test_getfile_builtin_class(self):
with self.assertRaises(TypeError) as e:
inspect.getfile(int)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix :func:`inspect.getfile` error message for custom module objects.
Loading