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

Dave Angel davea at ieee.org
Fri Dec 25 23:00:05 EST 2009


Dotan Barak wrote:
> <div class="moz-text-flowed" style="font-family: -moz-fixed">On 
> 25/12/2009 19:27, Gary Herron wrote:
>> Dotan Barak wrote:
>>
>> Recover the exception, and examine the tuple of args or the message 
>> string.
>> >>> try:
>> ...         eval("my_number < 10", {"__builtins__":None}, {})
>> ... except NameError,e:
>> ...         print e.args
>> ...         print e.message
>> ...
>> ("name 'my_number' is not defined",)
>> name 'my_number' is not defined
>>
> First of all, thank - I really appreciate your response.
> :)
>
> I must admit that i don't like the idea of parsing a string (if 
> tomorrow the format of the message will change,
> i will be in a deep trouble ...).
>
> Is there is another way which doesn't involve string parsing?
>
> Thanks
> Dotan
>
> </div>
>
I think there's a more fundamental question here.  You're apparently 
looking to build your own error message instead of using the one already 
generated.  But as you point out, you might end up parsing the existing 
error message in order to do that, and that's fragile coding.  My take 
is that if you're using "eval" in your code, your user is clearly a 
programmer.  So why are you not letting that programmer see the real 
error message, instead of trying to pretty it up?  You can add to the 
message, but shouldn't need to hide the original one.

To put it the other way around, if your user can't understand the python 
error messages, you should probably not be using unrestricted "eval" on 
something that user supplies.  Lots more errors than NameError, and many 
of them are more subtle and dangerous.

DaveA




More information about the Python-list mailing list