[Python-Dev] Bug in inspect module

Ewan Mellor ewan at xensource.com
Sat Mar 17 21:38:26 CET 2007


All,

I have a problem being reported (by Xen users) where inspect.stack() is
throwing IndexError.  I think that this is a bug in inspect.py -- findsource
generally throws IOError when it can't find a particular source file, but in
the case where it finds a source file, but that file is shorter than expected,
then findsource throws IndexError, and this is propagated all the way out of
inspect.stack().

I'm not sure why inspect.py is finding source files that don't match the code
being executed -- it seems to be dependent upon the install environment,
because it's not affecting most people.  That said, I think that it's
reasonable to cope with a too-short source file in the same way as we cope
with missing source files -- by throwing IOError from findsource and handling
that exception later.

Here's a patch.

Cheers,

Ewan Mellor, XenSource.

--- inspect.py.orig     2007-03-17 17:01:56.410399391 +0000
+++ inspect.py  2007-03-17 17:16:36.026005726 +0000
@@ -490,6 +490,8 @@
         if not hasattr(object, 'co_firstlineno'):
             raise IOError('could not find function definition')
         lnum = object.co_firstlineno - 1
+        if len(lines) - 1 < lnum:
+            raise IOError('source file is too short')
         pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
         while lnum > 0:
             if pat.match(lines[lnum]): break


More information about the Python-Dev mailing list