Why does the name undefined in the "exception" not cause a "NameError"?

I was surprised today to see that the following works without exception (at least in Python 2.7.3):

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

I would think that this should raise the value NameErrorin the REPL, similar to the following:

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

Does anyone know what is going on here?

+5
source share
1 answer

For the same reason, this does not raise an exception:

>>> True or ThingThatDoesNotExist

Python searches for names exactly when they need to be evaluated. Names that do not need to be evaluated are not looked up, and this is an unsuccessful search that throws an exception.

+4
source

All Articles