diff options
-rw-r--r-- | Lib/inspect.py | 7 | ||||
-rw-r--r-- | Lib/test/test_inspect.py | 10 |
2 files changed, 14 insertions, 3 deletions
diff --git a/Lib/inspect.py b/Lib/inspect.py index 781a532..3599e02 100644 --- a/Lib/inspect.py +++ b/Lib/inspect.py @@ -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__ diff --git a/Lib/test/test_inspect.py b/Lib/test/test_inspect.py index 028eeb9..ec04c85 100644 --- a/Lib/test/test_inspect.py +++ b/Lib/test/test_inspect.py @@ -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' |