raise statement on a conditional expression

后端 未结 4 445
梦如初夏
梦如初夏 2020-12-29 03:38

Following \"Samurai principle\", I\'m trying to do this on my functions but seems it\'s wrong...

return  if  else raise 

        
相关标签:
4条回答
  • 2020-12-29 04:02

    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
    
    0 讨论(0)
  • 2020-12-29 04:20

    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.

    0 讨论(0)
  • 2020-12-29 04:22

    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
    
    0 讨论(0)
  • 2020-12-29 04:26

    Well, you could test for the bool separately:

    if expr: raise exception('foo')
    return val
    

    That way, you could test for expr earlier.

    0 讨论(0)
提交回复
热议问题