[Python-Dev] fixing traceback.extract_stack() line numbers

Greg Klanderman gak@klanderman.net
Wed, 29 Jan 2003 13:49:58 -0500 (EST)


Hi,

I noticed that the extract_stack function in the traceback module only
gives the line information of the start of the function you are in
rather than the line you are on.  The following seems to be the
troublesome line:

|        lineno = f.f_lineno     # XXX Too bad if -O is used

Comparing the extract_stack function to extract_tb, also in the
traceback module, the latter calls a function tb_lineno to calculate
the correct line number.  Pattern matching off that function, I
defined 

| def frame_lineno(f):
|   c = f.f_code
|   if not hasattr(c, 'co_lnotab'):
|     return f.f_lineno
| 
|   tab = c.co_lnotab
|   line = c.co_firstlineno
|   stopat = f.f_lasti
|   addr = 0
|   for i in range(0, len(tab), 2):
|     addr = addr + ord(tab[i])
|     if addr > stopat:
|       break
|     line = line + ord(tab[i+1])
|   return line

and replaced the previously mentioned line in extract_stack as follows:

|        lineno = frame_lineno(f)

and the problem seems to be fixed; I get correct line numbers even
when compiled with -O.

Is there any reason this change shouldn't be incorporated into the
traceback module?  I can send a proper patch if you are interested.

Please include me in any followup, I am not subscribed to python-dev.

thanks
Greg Klanderman
gak@klanderman.net