Assume I have the following script:
def do_not_call_on_one(i):
if i == 1:
raise ValueError("You never listen.")
print "Success!"
do_not_call_on_one(1)
On excution, you will see the following traceback:
Traceback (most recent call last):
File "test.py", line 7, in <module>
do_not_call_on_one(1)
File "test.py", line 3, in do_not_call_on_one
raise ValueError("You never listen.")
ValueError: You never listen.
Is there some way to manipulate the call stack, such that the error is emitted from the line which is actually causing the problem, like so?:
Traceback (most recent call last):
File "test.py", line 7, in <module>
do_not_call_on_one(1)
ValueError: You never listen.
This would save developer time that would otherwise be wasted scanning the call stack, searching for the incorrectly used function, when the correct behavior could be defined ahead of time.
Is there anything in Python that would allow an exception to use a modified traceback?
Update
There are buitins which are replicating this functionality:
# In test.py:
int('a')
# Executing 'python test.py' yields:
Traceback (most recent call last):
File "test.py", line 1, in <module>
int('a')
ValueError: invalid literal for int() with base 10: 'a'
Note: The traceback does not descend into the int()
function to display a bunch of useless scopes (especially the unhelpful raise ValueError
itself).