diff -r f903cf864191 Doc/library/inspect.rst --- a/Doc/library/inspect.rst Thu Apr 18 19:37:06 2013 +0200 +++ b/Doc/library/inspect.rst Thu Apr 18 21:59:26 2013 +0100 @@ -340,7 +340,16 @@ Return in a single string any lines of comments immediately preceding the object's source code (for a class, function, or method), or at the top of the - Python source file (if the object is a module). + Python source file (if the object is a module). An :exc:`OSError` is raised + if the source code cannot be retrieved, and a :exc:`TypeError` is raised if + the object is a built-in module, class or function. + + .. versionchanged:: 3.4 + :exc:`OSError` is raised if the source code cannot be retrieved, rather + than returning ``None``. + + :exc:`TypeError` is raised if the object is a built-in module, class or + function. .. function:: getfile(object) diff -r f903cf864191 Lib/inspect.py --- a/Lib/inspect.py Thu Apr 18 19:37:06 2013 +0200 +++ b/Lib/inspect.py Thu Apr 18 21:59:26 2013 +0100 @@ -610,12 +610,10 @@ def getcomments(object): """Get lines of comments immediately preceding an object's source code. - Returns None when source can't be found. + An OSError is raised if the source code cannot be retrieved. A TypeError is + raised if object is a built-in module, class or function. """ - try: - lines, lnum = findsource(object) - except (OSError, TypeError): - return None + lines, lnum = findsource(object) if ismodule(object): # Look for a comment block at the top of the file. diff -r f903cf864191 Lib/test/test_inspect.py --- a/Lib/test/test_inspect.py Thu Apr 18 19:37:06 2013 +0200 +++ b/Lib/test/test_inspect.py Thu Apr 18 21:59:26 2013 +0100 @@ -2,6 +2,7 @@ import sys import types import unittest +import unittest.mock import inspect import linecache import datetime @@ -259,6 +260,11 @@ def test_getcomments(self): self.assertEqual(inspect.getcomments(mod), '# line 1\n') self.assertEqual(inspect.getcomments(mod.StupidGit), '# line 20\n') + self.assertRaisesRegex(TypeError, 'built-in', + inspect.getcomments, list) + # If the source file is unavailable, should raise OSError. + with unittest.mock.patch('inspect.getsourcefile', return_value=''): + self.assertRaises(OSError, inspect.getcomments, mod) def test_getmodule(self): # Check actual module @@ -277,6 +283,11 @@ def test_getsource(self): self.assertSourceEqual(git.abuse, 29, 39) self.assertSourceEqual(mod.StupidGit, 21, 46) + self.assertRaisesRegex(TypeError, 'built-in', + inspect.getcomments, list) + # If the source file is unavailable, should raise OSError. + with unittest.mock.patch('inspect.getsourcefile', return_value=""): + self.assertRaises(OSError, inspect.getcomments, mod) def test_getsourcefile(self): self.assertEqual(normcase(inspect.getsourcefile(mod.spam)), modfile)