Python – throwing an exception from the scope of the caller?

throwing an exception from the scope of the caller?… here is a solution to the problem.

throwing an exception from the scope of the caller?

< partition >

Let’s say 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)

When executed, 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 so that an error is emitted from the line that is actually causing the problem, like this? :

Traceback (most recent call last):
  File "test.py", line 7, in <module>
    do_not_call_on_one(1)
ValueError: You never listen.

This will save developers time that would otherwise be wasted scanning the call stack, searching for misused functions, and the correct behavior can be defined in advance.

Is there anything in Python that allows exceptions to use modified backtraceback?

Update

There are some buitins that are replicating this feature:

# 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: Backtracking does not go into the int() function to show a bunch of useless ranges (especially the useless raise ValueError itself).

Related Problems and Solutions