[英]raise statement on a conditional expression
遵循“武士原则”,我试图在我的功能上做到这一点,但似乎是错误的......
return <value> if <bool> else raise <exception>
有没有其他“美丽”的方式来做到这一点? 谢谢
内联/三元if
是表达式,而不是语句。 你的尝试意味着“如果bool,返回值,否则返回raise expression
的结果” - 这当然是无稽之谈,因为raise exception
本身就是一个语句而不是表达式。
内联无法做到这一点,你不应该这样做。 明确地做:
if not bool:
raise MyException
return value
如果你绝对要raise
在表达式中,你可以做
def raiser(ex): raise ex
return <value> if <bool> else raiser(<exception>)
如果函数中没有无条件raise
,则“尝试”返回raiser()
的返回值,该值将为None
。
我喜欢用断言来做,所以你要强调那个成员必须像合同一样。
>>> def foo(self):
... assert self.value, "Not Found"
... return self.value
好吧,你可以分别测试bool:
if expr: raise exception('foo')
return val
这样,您可以在之前测试expr
。
有一种方法可以在三元内部提高,诀窍是使用exec
:
def raising_ternary(x):
return x if x else exec("raise Exception('its just not true')")
正如你所看到的,用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.