Getting the name which is not defined from NameError in python
Asked Answered
S

4

8

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

Stifling answered 16/2, 2010 at 5:7 Comment(4)
If it's not defined, how can it have a value?Koloski
I want to extract the name, not the value. I said "the value 'a'", not "the value of a".Stifling
Why do you need to use eval? If you want to create a Python shell, this is not the right tool. If you want to create an expression evaluator for your application, this is not the right tool.Quadrisect
What would be the right tool? -.- You could include that in your previous comment...Stifling
K
6
>>> 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'
Koloski answered 16/2, 2010 at 5:15 Comment(0)
S
1
>>> import exceptions
>>> try:
...     a > 0
... except exceptions.NameError, e:
...     print e
... 
name 'a' is not defined
>>> 

You can parse exceptions string for '' to extract value.

Superstratum answered 16/2, 2010 at 5:14 Comment(0)
P
1

No import exceptions needed in Python 2.x

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

You assign the reference for 'a' as such:

>>> try:
...     a > 0
... except NameError as e:
...     locals()[e.message.split("'")[1]] = 0
...
>>> a
0
Preconception answered 5/6, 2013 at 1:35 Comment(0)
L
0

Python 3.10 added a name field to NameError, so for most cases, you can now simply use e.name.

(This won't work for libraries that don't explicitly pass name as a keyword argument to the error, but that's also an issue if you're analyzing the message; a simple raise NameError provides has no recoverable information about the name.)

Linalool answered 20/9 at 1:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.