Possible Duplicate:
How can I modify a Python traceback object when raising an exception?
Consider this toy example:
def twice(n):
_validate_twice_args(n)
return 2*n
def _validate_twice_args(n):
if type(n) != int:
raise TypeError('n must be an int')
twice(None)
--
Traceback (most recent call last):
File "demo.py", line 9, in <module>
twice(None)
File "demo.py", line 2, in twice
_validate_twice_args(n)
File "demo.py", line 7, in _validate_twice_args
raise TypeError('n must be an int')
TypeError: n must be an int
Even though the locus of the error is the call twice(None)
, the traceback refers to code that the person responsible for the error is not even aware of, ("_validate
who? I never called that! I don't even know what it is!"), and unnecessarily exposes code that should be "behind the API". Even in the absence of "private" helper functions like _validate_twice_args
, the stacktrace printed in response to bad arguments unnecessarily exposes internal code, and obscures the locus of the error.
For example, if one inlines the code of _validate_twice_args
, the stack trace looks like this:
Traceback (most recent call last):
File "demo.py", line 10, in <module>
twice(None)
File "demo.py", line 3, in twice
raise TypeError('n must be an int')
TypeError: n must be an int
To get an idea of what the stack trace for this sort of error should look like, here's the one resulting from a very similar type of error, the call twice()
instead of twice(None)
, but one that is raised by Python, before control is passed to twice
:
Traceback (most recent call last):
File "demo.py", line 9, in <module>
twice()
TypeError: twice() takes exactly 1 argument (0 given)
In this case too, the error lies in a call to twice
with an invalid arguments list. Accordingly the stack trace points directly to the locus of the error (and not to the line in the underlying [most likely C] code where the error was first detected, thank goodness). This is as it should be, IMO1.
How can I modify twice_args
and/or _validate_twice_args
so that the last line of the stacktrace refers to the source code line of the buggy call to twice
?
1I realize that opinions on what the stacktrace should say in such cases differ from mine, but these philosophical considerations are not the subject of this thread.
Edit: emphasized remarks in the original post, but apparently overlooked by the first two responders.