raise statement on a conditional expression raise statement on a conditional expression python python

raise statement on a conditional expression


If you absolutely want to raise in an expression, you could do

def raiser(ex): raise exreturn <value> if <bool> else raiser(<exception>)

This "tries" to return the return value of raiser(), which would be None, if there was no unconditional raise in the function.


Inline/ternary if is an expression, not a statement. Your attempt means "if bool, return value, else return the result of raise expression" - which is nonsense of course, because raise exception is itself a statement not an expression.

There's no way to do this inline, and you shouldn't want to. Do it explicitly:

if not bool:    raise MyExceptionreturn value


I like to do it with assertions, so you emphasize that that member must to be, like a contract.

>>> def foo(self):...     assert self.value, "Not Found"...     return self.value