From 9b1369e1bf6ac49a140417c019765065016f776d Mon Sep 17 00:00:00 2001 From: devdanzin <74280297+devdanzin@users.noreply.github.com> Date: Sun, 27 Oct 2024 08:06:55 -0300 Subject: [PATCH] Fix inspect.getsource for classes created in PyREPL. --- Lib/inspect.py | 5 +++-- Lib/test/test_pyrepl/test_pyrepl.py | 6 ++++++ 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/Lib/inspect.py b/Lib/inspect.py index ea0d992436eb17..1031db892bb90c 100644 --- a/Lib/inspect.py +++ b/Lib/inspect.py @@ -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__ diff --git a/Lib/test/test_pyrepl/test_pyrepl.py b/Lib/test/test_pyrepl/test_pyrepl.py index f29a7ffbd7cafd..ecf8ccb0aed4e2 100644 --- a/Lib/test/test_pyrepl/test_pyrepl.py +++ b/Lib/test/test_pyrepl/test_pyrepl.py @@ -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')