提高条件表达式的陈述

时间:2022-06-03 22:22:40

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 个解决方案

#1


15  

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.

内联/三元if是表达式,而不是语句。你的尝试意味着“如果bool,返回值,否则返回raise表达式的结果” - 这当然是无稽之谈,因为raise异常本身就是一个语句而不是表达式。

There's no way to do this inline, and you shouldn't want to. Do it explicitly:

内联无法做到这一点,你不应该这样做。明确地做:

if not bool:
    raise MyException
return value

#2


12  

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.

如果函数中没有无条件加注,则“尝试”返回raiser()的返回值,该值将为None。

#3


1  

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。

#4


1  

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


15  

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.

内联/三元if是表达式,而不是语句。你的尝试意味着“如果bool,返回值,否则返回raise表达式的结果” - 这当然是无稽之谈,因为raise异常本身就是一个语句而不是表达式。

There's no way to do this inline, and you shouldn't want to. Do it explicitly:

内联无法做到这一点,你不应该这样做。明确地做:

if not bool:
    raise MyException
return value

#2


12  

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.

如果函数中没有无条件加注,则“尝试”返回raiser()的返回值,该值将为None。

#3


1  

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。

#4


1  

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