]> granicus.if.org Git - python/commitdiff
allow "fake" filenames in findsource (closes #9284)
authorBenjamin Peterson <benjamin@python.org>
Sat, 11 Jun 2011 20:53:11 +0000 (15:53 -0500)
committerBenjamin Peterson <benjamin@python.org>
Sat, 11 Jun 2011 20:53:11 +0000 (15:53 -0500)
This allows findsource() to work in doctests.

A patch from Dirkjan Ochtman.

Lib/inspect.py
Lib/test/test_inspect.py
Misc/NEWS

index b0b2d3a8f502b0eeed86e5a96784c0e6162dfec1..c727530f0ea0dd74e5cd82a6c9bc7b5aafb59b12 100644 (file)
@@ -524,9 +524,13 @@ def findsource(object):
     or code object.  The source code is returned as a list of all the lines
     in the file and the line number indexes a line in that list.  An IOError
     is raised if the source code cannot be retrieved."""
-    file = getsourcefile(object)
-    if not file:
+
+    file = getfile(object)
+    sourcefile = getsourcefile(object)
+    if not sourcefile and file[0] + file[-1] != '<>':
         raise IOError('source code not available')
+    file = sourcefile if sourcefile else file
+
     module = getmodule(object, file)
     if module:
         lines = linecache.getlines(file, module.__dict__)
index d93ffec58b3764359989aa9c831816f13c3b868e..b8c9a1803c96a97ae5319f91c01f92d8d003df4f 100644 (file)
@@ -295,6 +295,23 @@ class TestRetrievingSourceCode(GetSourceBase):
         del sys.modules[name]
         inspect.getmodule(compile('a=10','','single'))
 
+    def test_proceed_with_fake_filename(self):
+        '''doctest monkeypatches linecache to enable inspection'''
+        fn, source = '<test>', 'def x(): pass\n'
+        getlines = linecache.getlines
+        def monkey(filename, module_globals=None):
+            if filename == fn:
+                return source.splitlines(True)
+            else:
+                return getlines(filename, module_globals)
+        linecache.getlines = monkey
+        try:
+            ns = {}
+            exec compile(source, fn, 'single') in ns
+            inspect.getsource(ns["x"])
+        finally:
+            linecache.getlines = getlines
+
 class TestDecorators(GetSourceBase):
     fodderFile = mod2
 
index b15da796f6d475258fe111e7b9648924f2e5100e..bbd076a5e3941195a78c1b5c9eaf8022648539df 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -16,6 +16,9 @@ Core and Builtins
 Library
 -------
 
+- Issue #9284: Allow inspect.findsource() to find the source of doctest
+  functions.
+
 - Issue #10694: zipfile now ignores garbage at the end of a zipfile.
 
 - Issue #11583: Speed up os.path.isdir on Windows by using GetFileAttributes