Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 2eed8b7

Browse files
committed
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.
1 parent 32970b8 commit 2eed8b7

2 files changed

Lines changed: 14 additions & 3 deletions

File tree

Lib/inspect.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -516,9 +516,10 @@ def getfile(object):
516516
return object.__file__
517517
raise TypeError('{!r} is a built-in module'.format(object))
518518
if isclass(object):
519-
object = sys.modules.get(object.__module__)
520-
if hasattr(object, '__file__'):
521-
return object.__file__
519+
if hasattr(object, '__module__'):
520+
object = sys.modules.get(object.__module__)
521+
if hasattr(object, '__file__'):
522+
return object.__file__
522523
raise TypeError('{!r} is a built-in class'.format(object))
523524
if ismethod(object):
524525
object = object.__func__

Lib/test/test_inspect.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -319,6 +319,16 @@ def test_getsourcefile(self):
319319
def test_getfile(self):
320320
self.assertEqual(inspect.getfile(mod.StupidGit), mod.__file__)
321321

322+
def test_getfile_class_without_module(self):
323+
class CM(type):
324+
@property
325+
def __module__(cls):
326+
raise AttributeError
327+
class C(metaclass=CM):
328+
pass
329+
with self.assertRaises(TypeError):
330+
inspect.getfile(C)
331+
322332
def test_getmodule_recursion(self):
323333
from types import ModuleType
324334
name = '__inspect_dummy'

0 commit comments

Comments
 (0)