Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does `if Exception` work in Python

In this answer https://stackoverflow.com/a/27680814/3456281, the following construct is presented

a=[1,2]
while True:
    if IndexError:
        print ("Stopped.")
        break
    print(a[2])

which actually prints "Stopped." and breaks (tested with Python 3.4.1).

Why?! Why is if IndexError even legal? Why does a[2] not raise an IndexError with no try ... except around?

like image 582
Jasper Avatar asked Dec 28 '14 22:12

Jasper


2 Answers

All objects have a boolean value. If not otherwise defined, that boolean value is True.

So this code is simply the equivalent of doing if True; so execution reaches the break statement immediately and the print is never reached.

like image 179
Daniel Roseman Avatar answered Sep 20 '22 19:09

Daniel Roseman


View the Python documentation, section Truth Value Testing under Built-in Types of The Python Standard Library. The first sentence, and the first sentence after the last bullet point answers your question.

Any object can be tested for truth value ...

and

All other values are considered true — so objects of many types are always true.

Here's the full text of the documentation, (content in brackets, [], are added as an augmentation):

5.1. Truth Value Testing

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:

  • None

  • False

  • zero of any numeric type, for example, 0, 0L, 0.0, 0j.

  • any empty sequence, for example, '', (), [].

  • any empty mapping, for example, {}.

  • instances of user-defined classes, if the class defines a __bool__() [__nonzero__() in Python 2] or __len__() method, when that method returns the integer zero or bool value False. [See Data Model, Special Method Names, section Basic Customization, of The Python Language Reference]

All other values are considered true — so objects of many types are always true.

Operations and built-in functions that have a Boolean result always return 0 or False for false and 1 or True for true, unless otherwise stated. (Important exception: the Boolean operations or and and always return one of their operands.)

Conclusion

So since Exception does not have a __bool__, __nonzero__, or __len__, (nor fall under the other conditions listed above) an Exception object will always test as True in a boolean context.

like image 35
Russia Must Remove Putin Avatar answered Sep 19 '22 19:09

Russia Must Remove Putin