Skip to content

Commit

Permalink
Fix inspect.getsource for classes created in PyREPL.
Browse files Browse the repository at this point in the history
  • Loading branch information
devdanzin committed Oct 27, 2024
1 parent dad3453 commit 9b1369e
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 2 deletions.
5 changes: 3 additions & 2 deletions Lib/inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -818,11 +818,12 @@ def getfile(object):
raise TypeError('{!r} is a built-in module'.format(object))
if isclass(object):
if hasattr(object, '__module__'):
# Protect against fetching the wrong source in PyREPL
if object.__module__ == '__main__':
raise OSError('source code not available')
module = sys.modules.get(object.__module__)
if getattr(module, '__file__', None):
return module.__file__
if object.__module__ == '__main__':
raise OSError('source code not available')
raise TypeError('{!r} is a built-in class'.format(object))
if ismethod(object):
object = object.__func__
Expand Down
6 changes: 6 additions & 0 deletions Lib/test/test_pyrepl/test_pyrepl.py
Original file line number Diff line number Diff line change
Expand Up @@ -1318,6 +1318,12 @@ def test_null_byte(self):
self.assertEqual(exit_code, 0)
self.assertNotIn("TypeError", output)

def test_inspect_getsource(self):
code = "import inspect\nclass A: pass\nprint(inspect.getsource(A))"
output, exit_code = self.run_repl(code)
self.assertNotEqual(exit_code, 0)
self.assertIn("OSError('source code not available')", output)

def test_readline_history_file(self):
# skip, if readline module is not available
readline = import_module('readline')
Expand Down

0 comments on commit 9b1369e

Please sign in to comment.