Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't an undefined name in an "except" raise a NameError?

Tags:

python

I was surprised today to see that the following works with no exceptions (in Python 2.7.3 at least):

>>> try:
...     pass
... except ThingThatDoesNotExist:
...     print "bad"
...
>>>

I would have thought that this should raise a NameError in the REPL, similar to how the following would:

>>> x = ThingThatDoesNotExist
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'ThingThatDoesNotExist' is not defined

Anyone have any idea what's going on here?

like image 308
dcrosta Avatar asked Oct 04 '22 11:10

dcrosta


1 Answers

The same reason this does not raise a exception:

>>> True or ThingThatDoesNotExist

Python looks up names exactly the moment they need to be evaluated. Names that don't need to be evaluated are not looked up and it's the failed lookup that raises the exception.

like image 124
Jochen Ritzel Avatar answered Oct 13 '22 11:10

Jochen Ritzel