Is it possible to get the erroneous variable when getting a NameError exception?
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Fri Dec 25 12:09:48 EST 2009
On Fri, 25 Dec 2009 17:29:48 +0200, Dotan Barak wrote:
> 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).
>
> <--snip start-->
> >>> eval("my_number < 10", {"__builtins__":None}, {})
> 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
--
Steven
More information about the Python-list
mailing list