30
votes

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

4
What is that Samurai here? What do you think about adding some details? - Wolf
the Samurai Principle - Return victorious, or not at all. If a function fulfills its responsibilities, return the appropiate result object, and if it doesn't then throw an Exception. - F.D.F.
Oh, I see. Maybe some link would be good, such as Samurai Principle - Wolf

4 Answers

23
votes

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
25
votes

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.

2
votes

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
1
votes

Well, you could test for the bool separately:

if expr: raise exception('foo')
return val

That way, you could test for expr earlier.