diff -r 64d9569b4e1f Doc/library/inspect.rst --- a/Doc/library/inspect.rst Sat Oct 12 01:41:49 2013 +0200 +++ b/Doc/library/inspect.rst Sun Oct 13 11:40:45 2013 +0800 @@ -341,7 +341,9 @@ 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). If the object's source code + is unavailable, return ``None``. This could happen if the object has been + defined in C or interactive shell. .. function:: getfile(object) diff -r 64d9569b4e1f Lib/test/test_inspect.py --- a/Lib/test/test_inspect.py Sat Oct 12 01:41:49 2013 +0200 +++ b/Lib/test/test_inspect.py Sun Oct 13 11:40:45 2013 +0800 @@ -10,14 +10,18 @@ import shutil import functools import importlib +import textwrap +import imp from os.path import normcase try: from concurrent.futures import ThreadPoolExecutor except ImportError: ThreadPoolExecutor = None -from test.support import run_unittest, TESTFN, DirsOnSysPath -from test.script_helper import assert_python_ok, assert_python_failure +from test.support import run_unittest, TESTFN, DirsOnSysPath, unlink +from test.script_helper import (assert_python_ok, + assert_python_failure, + make_script) from test import inspect_fodder as mod from test import inspect_fodder2 as mod2 @@ -280,8 +284,26 @@ 'An\nindented\ndocstring.') def test_getcomments(self): - self.assertEqual(inspect.getcomments(mod), '# line 1\n') - self.assertEqual(inspect.getcomments(mod.StupidGit), '# line 20\n') + source_content = textwrap.dedent("""\ + # line 1 + 'A module docstring.' + + # line 20 + class StupidGit: + pass + """) + source_file = TESTFN + '.py' + self.addCleanup(unlink, source_file) + make_script('', TESTFN, source_content) + spam = imp.load_source('spam', source_file) + self.assertEqual(inspect.getcomments(spam), '# line 1\n') + self.assertEqual(inspect.getcomments(spam.StupidGit), '# line 20\n') + # If the source file is unavailable, it should return None. + unlink(source_file) + del linecache.cache[source_file] + self.assertIsNone(inspect.getcomments(spam)) + # If the object has been defined in C, it should return None. + self.assertIsNone(inspect.getcomments(list)) def test_getmodule(self): # Check actual module