Getting a name that is not defined in NameError in python

As you know, if we just 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 to catch the exception / error and extract the value 'a' from it. I need this because I am exchanging dynamically generated expressions and would like to get names that are not defined in them.

I hope I get it. Thank you Manuel

+7
python exception-handling expression dynamic-data nameerror
source share
3 answers
 >>> import re >>> try: ... a>0 ... except (NameError,),e: ... print re.findall("name '(\w+)' is not defined",str(e))[0] a 

If you do not want to use regex, you can do something like this

 >>> str(e).split("'")[1] 'a' 
+6
source share
 >>> import exceptions >>> try: ... a > 0 ... except exceptions.NameError, e: ... print e ... name 'a' is not defined >>> 

You can parse the exception string for '' to retrieve the value.

+1
source share

No import exceptions needed in Python 2.x

 >>> try: ... a > 0 ... except NameError as e: ... print e.message.split("'")[1] ... a >>> 

You assign a link to 'a' as such:

 >>> try: ... a > 0 ... except NameError as e: ... locals()[e.message.split("'")[1]] = 0 ... >>> a 0 
0
source share

All Articles