]> granicus.if.org Git - python/commitdiff
bpo-37173: Show passed class in inspect.getfile error (GH-13861)
authorPhilipp A <flying-sheep@web.de>
Sat, 8 Jun 2019 12:05:46 +0000 (14:05 +0200)
committerMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Sat, 8 Jun 2019 12:05:46 +0000 (05:05 -0700)
Currently, inspect.getfile(str) will report nonsense:

```pytb
>>> inspect.getfile(str)
TypeError: <module 'builtins' (built-in)> is a built-in class
```

This fixes that

https://bugs.python.org/issue37173

Lib/inspect.py
Lib/test/test_inspect.py
Misc/NEWS.d/next/Library/2019-06-08-11-33-48.bpo-37173.0e_8gS.rst [new file with mode: 0644]

index 91d209dc64bc9fd4de97d1306c6a85280fd92578..99a580bd2f23500a60010362961634c7295f2891 100644 (file)
@@ -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__
index 83a5f7ec1f5385d58eab68e5875764f39a329499..1cd4ea28939d8ac0fd8e270cef0445bc367f42e1 100644 (file)
@@ -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('<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
diff --git a/Misc/NEWS.d/next/Library/2019-06-08-11-33-48.bpo-37173.0e_8gS.rst b/Misc/NEWS.d/next/Library/2019-06-08-11-33-48.bpo-37173.0e_8gS.rst
new file mode 100644 (file)
index 0000000..e996f97
--- /dev/null
@@ -0,0 +1 @@
+The exception message for ``inspect.getfile()`` now correctly reports the passed class rather than the builtins module.
\ No newline at end of file