From c5daae4ef6d09269c95ed1023e76932cc179f309 Mon Sep 17 00:00:00 2001 From: "Miss Islington (bot)" <31488909+miss-islington@users.noreply.github.com> Date: Sat, 8 Jun 2019 05:24:59 -0700 Subject: [PATCH] bpo-37173: Show passed class in inspect.getfile error (GH-13861) Currently, inspect.getfile(str) will report nonsense: ```pytb >>> inspect.getfile(str) TypeError: is a built-in class ``` This fixes that https://bugs.python.org/issue37173 (cherry picked from commit d407d2a7265f6102e51a1d62b3fd28b4f7a78d16) Co-authored-by: Philipp A --- Lib/inspect.py | 6 +++--- Lib/test/test_inspect.py | 18 ++++++++++++++++++ .../2019-06-08-11-33-48.bpo-37173.0e_8gS.rst | 1 + 3 files changed, 22 insertions(+), 3 deletions(-) create mode 100644 Misc/NEWS.d/next/Library/2019-06-08-11-33-48.bpo-37173.0e_8gS.rst diff --git a/Lib/inspect.py b/Lib/inspect.py index 91d209dc64..99a580bd2f 100644 --- a/Lib/inspect.py +++ b/Lib/inspect.py @@ -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__ diff --git a/Lib/test/test_inspect.py b/Lib/test/test_inspect.py index 83a5f7ec1f..1cd4ea2893 100644 --- a/Lib/test/test_inspect.py +++ b/Lib/test/test_inspect.py @@ -513,6 +513,24 @@ class TestRetrievingSourceCode(GetSourceBase): 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('