Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm writing a custom logging system for a project. If a function throws an exception, I want to log its local variables. Is it possible to access the raising function's local variables from the except block that caught the exception? For example:

def myfunction():     v1 = get_a_value()     raise Exception()  try:     myfunction() except:     # can I access v1 from here? 
like image 870
davidscolgan Avatar asked Jan 30 '12 04:01

davidscolgan


People also ask

What happens when an exception is thrown Python?

As you saw earlier, when syntactically correct code runs into an error, Python will throw an exception error. This exception error will crash the program if it is unhandled. The except clause determines how your program responds to exceptions.

How do you catch specific exceptions in Python?

Catching Specific Exceptions in PythonA try clause can have any number of except clauses to handle different exceptions, however, only one will be executed in case an exception occurs. We can use a tuple of values to specify multiple exceptions in an except clause.

What are your options for recovering from an exception in your script in Python?

Try and Except Statement - Catching Exceptions In Python, we catch exceptions and handle them using try and except code blocks. The try clause contains the code that can raise an exception, while the except clause contains the code lines that handle the exception.

Does catching an exception stop execution Python?

except block is completed and the program will proceed. However, if an exception is raised in the try clause, Python will stop executing any more code in that clause, and pass the exception to the except clause to see if this particular error is handled there.


1 Answers

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.

like image 102
David Z Avatar answered Sep 28 '22 23:09

David Z