[英]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
谢谢
Inline/ternary if
is an expression, not a statement. 内联/三元
if
是表达式,而不是语句。 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. 你的尝试意味着“如果bool,返回值,否则返回
raise expression
的结果” - 这当然是无稽之谈,因为raise exception
本身就是一个语句而不是表达式。
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 如果你绝对要
raise
在表达式中,你可以做
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. 如果函数中没有无条件
raise
,则“尝试”返回raiser()
的返回值,该值将为None
。
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
Well, you could test for the bool separately: 好吧,你可以分别测试bool:
if expr: raise exception('foo')
return val
That way, you could test for expr
earlier. 这样,您可以在之前测试
expr
。
There is a way to raise inside of a ternary, the trick is to use exec
:有一种方法可以在三元内部提高,诀窍是使用
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:正如你所看到的,用
True
调用它会做三元的第一部分,用False
调用它会引发异常:
>>> 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
>>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.