Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the name which is not defined from NameError in python

As you know, if we simply do:

>>> a > 0
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    a > 0
NameError: name 'a' is not defined

Is there a way of catching the exception/error and extracting from it the value 'a'. I need this because I'm evaluating some dynamically created expressions, and would like to retrieve the names which are not defined in them.

Hope I made myself clear. Thanks! Manuel

like image 623
Manuel Araoz Avatar asked Feb 16 '10 05:02

Manuel Araoz


1 Answers

>>> import re
>>> try:
...     a>0
... except (NameError,),e:
...     print re.findall("name '(\w+)' is not defined",str(e))[0]
a

If you don't want to use regex, you could do something like this instead

>>> str(e).split("'")[1]
'a'
like image 136
John La Rooy Avatar answered Oct 12 '22 22:10

John La Rooy