Hi,
Given:
def affine(x, y, z):
return x + mul(y, z)
def mul(p, q):
return p * q
def test():
a = 5
b = 6
c = 'fake'
d = affine(a, b, c)
test()
Running it I get the following traceback. The trailing comments are additions which I would like to implement:
henry@henry-gs65:~$ python tb.py
Traceback (most recent call last):
File "tb.py", line 13, in <module>
test()
File "tb.py", line 11, in test
d = affine(a, b, c) # a = 5, b = 6, c = 'fake'
File "tb.py", line 2, in affine
return x + mul(y, z) # y = 6, z = 'fake'
TypeError: unsupported operand type(s) for +: 'int' and 'str'
I would like to write a custom sys.excepthook
which provides comments showing the values of the local variables specifically at the call sites of lower frames. The difficulty is that, while each frame object provides frame.f_locals
and frame.f_globals
and also frame.f_lineno
identifying the current execution line, there seems no direct way to get the identifiers of the currently executing line.
My thoughts are: grab the code text using inspect.getsourcelines(frame.f_code)
and then get the executing line(s) using frame.f_lineno
. Then parse the code string using ast.parse
, and then retrieve the identifiers from the parse tree.
This seems like it would be quite error proned though. Is there a better way?