mirror of
				https://github.com/python/cpython.git
				synced 2025-11-04 07:31:38 +00:00 
			
		
		
		
	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.
This commit is contained in:
		
							parent
							
								
									32970b8dec
								
							
						
					
					
						commit
						2eed8b7da0
					
				
					 2 changed files with 14 additions and 3 deletions
				
			
		| 
						 | 
				
			
			@ -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__
 | 
			
		||||
| 
						 | 
				
			
			
 | 
			
		|||
| 
						 | 
				
			
			@ -319,6 +319,16 @@ def test_getsourcefile(self):
 | 
			
		|||
    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'
 | 
			
		||||
| 
						 | 
				
			
			
 | 
			
		|||
		Loading…
	
	Add table
		Add a link
		
	
		Reference in a new issue