Be careful, the expression you are looking for does not really do what you expect.
The "ternary"% syntax a if b else c
requires that both a
as b
, as c
are expressions, that is, have a value (the b
will be interpreted by the context as a boolean). It is intended to be used on the right side of an assignment, as in:
r = a if b else c
Neither a
, nor b
, nor c
can be commands, but expressions (a call to a function counts as an expression, since it returns a value and then the returned value would be used).
raise
is not an expression. It is a command. That's why this does not work:
r = raise Exception() if b else c
Not this:
r = a if b else raise Exception()
Not this:
a if b else raise Exception()
So how does this work?
raise Exception() if b else c
Well, because Python is seeing it like this:
raise (Exception() if b else c)
That is, the ternary operator is being applied to decide which exception is raised, and not to decide whether or not an exception is raised. If b
is evaluated as true, the exception Exception()
will be raised and if not, the exception result of evaluating c
.
If you try:
raise ValueError('Se esperaba un boleano') if not isinstance(boleano, bool) else None
then if you do not have the boolano, ValueError()
will be raised, but if you have the boolean it will try to raise None
, which is not a valid exception and will cause another exception TypeError
( exceptions must derive from BaseException )
The recommended form would therefore be:
if not isinstance(boleano, bool): raise ValueError('Se esperaba un boleano')
that is also a single line and more readable.