Can I get the local variables of a Python function from which an exception was thrown?

It’s generally cleaner design to pass the value to the exception, if you know that your exception handling code is going to need it. However, if you’re writing a debugger or something like that, where you will need to access variables without knowing which ones they are in advance, you can access an arbitrary variable in the context where the exception was thrown:

def myfunction():
    v1 = get_a_value()
    raise Exception()

try:
    myfunction()
except:
    # can I access v1 from here?
    v1 = inspect.trace()[-1][0].f_locals['v1']

The functionality of the trace function, and the format of the traceback objects it deals with, are described in the inspect module documentation.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)