Get variable name causing UnboundLocalError

When I invoke a def, I get the UnboundLocalError message.
Is there a way using an except statement to ge the name of the variable causing the error?
I have the following code, but it does not give me the name of the variable causing the error.

except Exception as e:
    exception_type, exception_object, exception_traceback = sys.exc_info() 
    filename = exception_traceback.tb_frame.f_code.co_filename
    line_number = exception_traceback.tb_lineno
    exceptiontypestr = str(exception_type)[8:-2]'%m-%d-%Y %I:%M%p')
    print("error occurred: " , exceptiontypestr, " at linenumber = ",line_number)
    print("program name = ",filename)

The .args of this UnboundLocalError will be a tuple that contains the complete error message string. For example:

>>> def broken():
...      a += 1
>>> try:
...     broken()
... except UnboundLocalError as e:
...     print(e.args)
("local variable 'a' referenced before assignment",)

However, the exact contents of the string are allowed to vary with the Python version.

More importantly, you should not be writing code in the first place where this is a concern. If you are trying to debug the code, then don’t catch exceptions that indicate a problem in the code; exception handling is for problems that result from bad input to the program. If you are for example doing some strange thing with dynamically created variables, so that you can’t really be sure what variables you will have just by reading and debugging the code, then don’t do that; instead, use dictionaries and lists to hold structured data.

This is way too complicated for the kind of task that you describe, and it gives the impression that you are just trying to look up code and use whatever seems to work, without understanding it. This is also a bad habit. (In particular, it makes no real sense to use stuff like sys.exc_info inside an ordinary exception handler; e already means the same object as exception_object in this code, and you can more easily get the type as type(e) and the traceback as e.__traceback__. Normal efforts to log errors won’t care about the traceback, either; if you did care then you should normally just let the program crash and read it. As for the type, you should normally be specifying a particular exception type that you’re interested in with except anyway, like in my example - so you should already know the type.)


Many thanks for you response.
The exception was there to catch an error from bad date and write to an error log.

I removed the exception code and got the name of the local variable that caused the issue.
I did not intentionally use a variable before assignment.

I corrected my error in the code and the problem is solved.

Thanks again. YouR response is very much appreciated.