Search code examples
pythonexceptionconditional-statementsraise

raise statement on a conditional expression


How do I elegantly implement the "Samurai principle" (return victorious, or not at all) on my functions?

return <value> if <bool> else raise <exception>

Solution

  • 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