Why does using `or` within an except clause not cause a SyntaxError? Is there a valid use for it?
In except e
, e
can be any valid Python expression:
try1_stmt ::= "try" ":" suite ("except" [expression ["as" identifier]] ":" suite)+ ...
[..] For an
except
clause with an expression, that expression is evaluated, and the clause matches the exception if the resulting object is “compatible” with the exception. An object is compatible with an exception if it is the class or a base class of the exception object or a tuple containing an item compatible with the exception.https://docs.python.org/3/reference/compound_stmts.html#the-try-statement
The expression IndexError or KeyError
yields the value IndexError
. So this is equivalent to:
except IndexError:
...