raise statement on a conditional expression

F.D.F. picture F.D.F. · Apr 24, 2012 · Viewed 16.5k times · Source

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

Answer

glglgl picture glglgl · Apr 24, 2012

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.