summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorYury Selivanov <yselivanov@sprymix.com>2014-01-27 18:24:56 (GMT)
committerYury Selivanov <yselivanov@sprymix.com>2014-01-27 18:24:56 (GMT)
commit2eed8b7da06fe865b6246590d4b13cf723f547cd (patch)
treeef270a1a052c0ffd6146a304e9a34b4d4f155590
parent32970b8decc1bb96058898c6cef5a98b21bcf60b (diff)
downloadcpython-2eed8b7da06fe865b6246590d4b13cf723f547cd.zip
cpython-2eed8b7da06fe865b6246590d4b13cf723f547cd.tar.gz
cpython-2eed8b7da06fe865b6246590d4b13cf723f547cd.tar.bz2
inspect.getfile: Don't crash on classes without '__module__' attribute #20372
Some classes defined in C may not have the '__module__' attribute, so we now handle this case to avoid having unexepected AttributeError.
-rw-r--r--Lib/inspect.py7
-rw-r--r--Lib/test/test_inspect.py10
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'