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

Gary Herron gherron at islandtraining.com
Fri Dec 25 16:16:27 EST 2009


Dotan Barak wrote:
> 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
OK.  Try this:  Executing your code attempts to lookup variables in a 
local dictionary.   You can rig up a local dictionary of your own 
choosing -- in this case, I have it print the name of any variable that 
is being looked up before actually doing the lookup.    But at that 
point, you have what you want, that is, the name as a string -- you can 
do with it as you will -- record it, or print your nice error, or ...

You probably want to change my def of __getitem__ to attempt the lookup 
first -- if that succeeds, return the value -- if it fails, then handle 
the error.

Good luck,

Gary Herron



class D(dict):
    def __getitem__(self, name):
        print 'retrieving', name
        return dict.__getitem__(self,name)

locals = D(b=123) # Defines b in a local dictionary
exec("a=2*b", locals)  # Looks up b in locals
print locals['a'] # Returns the result (stored in 'a' in locals)

locals = D() # Does not define b in the local dictionary
exec("a=2*b", locals) # Fails to find b in locals




More information about the Python-list mailing list