Python exception backtrace tells me where the line ends, where does it start?

When a Python exception is thrown by code that spans multiple lines, for example:

   myfoos = [foo("bar",
                "baz",
                "quux",
                 i) for i in range(10)]

      

Python will report the line number of the last line and show a snippet of code from that line:

Traceback (most recent call last):
  File "test.py", line 4, in <module>
    i) for i in range(10)]
NameError: name 'foo' is not defined

      

Is there a way to determine what the first line is? Is there a way to catch the exception and manipulate the traceback object to be able to report something like this:

Traceback (most recent call last):
 File "test.py", lines 1-4 in <module>
   myfoos = [foo("bar",
                "baz",
                "quux",
                 i) for i in range(10)]
 NameError: name 'foo' is not defined

      

+1


source to share


2 answers


Finding the beginning of a string will be very difficult. You will have to either disassemble Python, or perhaps dig into the compiled bytecode. There are modules in the standard library for parsing Python, but I can tell you from experience that interpreting their output is black art. And I'm not sure if the compiled bytecode has an answer either ...



+2


source


In the try / except block, you can exclude the NameError and try setting the NameError.lineno, although I'm not entirely sure what or how it works, but it's the best I've found this way.

try:
    somecode
except NameError
    NameError.lineno = [1,4]

      



You will need to figure out where the assertion starts and ends somehow, as well as which operator is raising the error.

Hope it helps

0


source







All Articles