Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

raise statement on a conditional expression

Following "Samurai principle", I'm trying to do this on my functions but seems it's wrong...

return <value> if <bool> else raise <exception> 

Is there any other "beautiful" way to do this? Thanks

like image 500
F.D.F. Avatar asked Apr 24 '12 10:04

F.D.F.


People also ask

How do you raise a statement in Python?

Python raise Keyword is used to raise exceptions or errors. The raise keyword raises an error and stops the control flow of the program. It is used to bring up the current exception in an exception handler so that it can be handled further up the call stack.

How do you raise an exception in Python?

As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword.


2 Answers

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

def raiser(ex): raise ex  return <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.

like image 123
glglgl Avatar answered Sep 25 '22 23:09

glglgl


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 MyException return value 
like image 30
Daniel Roseman Avatar answered Sep 22 '22 23:09

Daniel Roseman