How do I elegantly implement the "Samurai principle" (return victorious, or not at all) on my functions?
return <value> if <bool> else raise <exception>
How do I elegantly implement the "Samurai principle" (return victorious, or not at all) on my functions?
return <value> if <bool> else raise <exception>
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
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.
{'f': os.environ.get('FOO') or raise_foobar(), ...}
–
Pledge 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
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
There is a way to raise inside of a ternary, the trick is to use exec
:
def raising_ternary(x):
return x if x else exec("raise Exception('its just not true')")
As you can see calling it with True
will do the first part of the ternary and calling it with False
will raise the exception:
>>> def raising_ternary(x):
... return x if x else exec("raise Exception('its just not true')")
...
>>> raising_ternary(True)
True
>>> raising_ternary(False)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in raising_ternary
File "<string>", line 1, in <module>
Exception: its just not true
>>>
exec()
is dangerous and shouldn't be used this way. –
Tauto Well, you could test for the bool separately:
if expr: raise exception('foo')
return val
That way, you could test for expr
earlier.
© 2022 - 2024 — McMap. All rights reserved.