bug in inspect.getsource

Bengt Richter bokr at oz.net
Thu Dec 26 16:54:36 EST 2002


On 26 Dec 2002 09:33:44 -0800, mis6 at pitt.edu (Michele Simionato) wrote:

>It seems I have found a bug in inspect.getsource.
>I am using Python 2.2.2 on Red-Hat 7.3. Here is the problem.
>
>--begin bug.py
>
>import inspect
>def f(x): return x
>print inspect.getsource(f)
>
>--end bug.py
>
>% python bug.py
>Traceback (most recent call last):
>  File "bug.py", line 3, in ?
>    print inspect.getsource(f)
>  File "/usr/local/lib/python2.2/inspect.py", line 520, in getsource
>    return string.join(lines, '')
>  File "/usr/local/lib/python2.2/string.py", line 131, in join
>    return sep.join(words)
>TypeError: sequence expected, NoneType found
>
>Notice that
> 
>--begin noproblem.py
>
>import inspect
>def f(x): 
>    return x
>print inspect.getsource(f)
>
>--end noproblem.py
>
>works:
>
>% python noproblem.py
>def f(x):
>    return x
>
>I discovered this bug in trying to retrieve the source code for
>lambda expressions like f=lambda x: x (same error message).
>For lambda expression I don't know a workaround as that in
>noproblem.py. Any hint ?
>
>
You could try this change until someone can very it:
(I am too tired not to have overlooked something, but
it seems to get past the bug file).

--- origlib\inspect.py  Sun Mar 17 12:51:30 2002
+++ lib\inspect.py      Thu Dec 26 13:57:43 2002
@@ -484,11 +484,18 @@
             if type == tokenize.NAME: self.started = 1
         elif type == tokenize.NEWLINE:
             self.last = srow
+            self.started = 2 # look for indent or new block at level 0 ??
         elif type == tokenize.INDENT:
             self.indent = self.indent + 1
         elif type == tokenize.DEDENT:
             self.indent = self.indent - 1
             if self.indent == 0: raise EndOfBlock, self.last
+        elif self.started == 2:
+            if type not in (tokenize.NL, tokenize.COMMENT):
+                self.started = 1
+                if self.indent == 0: raise EndOfBlock, self.last
+        if type == tokenize.ENDMARKER:
+            raise EndOfBlock, self.last

 def getblock(lines):
     """Extract the block of code at the top of the given list of lines."""

Regards,
Bengt Richter



More information about the Python-list mailing list