raise 条件表达式上的语句

问题描述

遵循武士原则",我正在尝试在我的功能上执行此操作,但似乎是错误的......

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


解决方案

内联/三元 if 是表达式,而不是语句.您的尝试意味着如果 bool,返回值,否则返回 raise 表达式 的结果" - 这当然是无稽之谈,因为 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

相关文章