Is it possible to get the erroneous variable when getting a NameErrorexception?

D

Dotan Barak

Hi.

I'm trying to evaluate a string and getting a NameError
(it is expected, since the variable my_number wasn't provided in the
"locals" dictionary).

Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<string>", line 0, in ?
NameError: name 'my_number' is not defined
<--snip end-->

My question is: how can i know which variable name / symbol causes the
NameError exception?
In my example, this symbol is my_number.

Using that information, I will be able to print a nice error message to
the user.


Thanks
Dotan
 
S

Steven D'Aprano

Hi.

I'm trying to evaluate a string and getting a NameError (it is expected,
since the variable my_number wasn't provided in the "locals"
dictionary).


Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<string>", line 0, in ?
NameError: name 'my_number' is not defined
<--snip end-->

My question is: how can i know which variable name / symbol causes the
NameError exception?
In my example, this symbol is my_number.

Using that information, I will be able to print a nice error message to
the user.

You mean just like the error message that Python already prints?

NameError: name 'my_number' is not defined

Don't waste your time re-inventing the wheel. But if you do insist on
reinventing the wheel, here are some tools to help you:

try:
my_number
except NameError, e:
print str(e)
print type(e)
print e.args
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,266
Messages
2,571,082
Members
48,773
Latest member
Kaybee

Latest Threads

Top