inspect.getfile: Don't crash on classes without '__module__' attribute #20372
authorYury Selivanov <yselivanov@sprymix.com>
Mon, 27 Jan 2014 18:24:56 +0000 (13:24 -0500)
committerYury Selivanov <yselivanov@sprymix.com>
Mon, 27 Jan 2014 18:24:56 +0000 (13:24 -0500)
Some classes defined in C may not have the '__module__' attribute, so
we now handle this case to avoid having unexepected AttributeError.

Lib/inspect.py
Lib/test/test_inspect.py

index 781a5320a0a705f02d574b6f8eb6e03f8145bef3..3599e028ed41ba67b890745989deee3ce5631012 100644 (file)
@@ -516,9 +516,10 @@ def getfile(object):
             return object.__file__
         raise TypeError('{!r} is a built-in module'.format(object))
     if isclass(object):
-        object = sys.modules.get(object.__module__)
-        if hasattr(object, '__file__'):
-            return object.__file__
+        if hasattr(object, '__module__'):
+            object = sys.modules.get(object.__module__)
+            if hasattr(object, '__file__'):
+                return object.__file__
         raise TypeError('{!r} is a built-in class'.format(object))
     if ismethod(object):
         object = object.__func__
index 028eeb9caa1d89a24e734314f153ca91d10221e6..ec04c8590bfbd307ea4e5bd44c4fb69ca5360f35 100644 (file)
@@ -319,6 +319,16 @@ class TestRetrievingSourceCode(GetSourceBase):
     def test_getfile(self):
         self.assertEqual(inspect.getfile(mod.StupidGit), mod.__file__)
 
+    def test_getfile_class_without_module(self):
+        class CM(type):
+            @property
+            def __module__(cls):
+                raise AttributeError
+        class C(metaclass=CM):
+            pass
+        with self.assertRaises(TypeError):
+            inspect.getfile(C)
+
     def test_getmodule_recursion(self):
         from types import ModuleType
         name = '__inspect_dummy'