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?
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.
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 valueFalse
. [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
orFalse
for false and1
orTrue
for true, unless otherwise stated. (Important exception: the Boolean operationsor
andand
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With