How to make a line break on the Python ternary operator?

后端 未结 3 957
逝去的感伤
逝去的感伤 2020-12-25 10:35

Sometimes a line containing a ternary operator in Python gets too long:

answer = \'Ten for that? You must be mad!\' if does_not_haggle(brian) else \"It\'s wo         


        
3条回答
  •  星月不相逢
    2020-12-25 10:52

    Bear in mind this advice from The Zen of Python: "Readability counts."

    The ternary operator is most readable when it is all on one line.

    x = y if z else w

    When your conditions or variables push the line past 79 characters (see PEP8), readability begins to suffer. (Readability is also why dict/list comprehensions are best kept short.)

    So, rather than trying to break the line using parentheses, you might find it is more readable if you convert it to a regular if block.

    if does_not_haggle(brian):
        answer = 'Ten for that? You must be mad!'
    else:
        answer = "It's worth ten if it's worth a shekel."
    

    BONUS: The above refactoring reveals another readability issue: does_not_haggle is inverted logic. This would be even more readable, if you can rewrite the function:

    if haggles(brian):
        answer = "It's worth ten if it's worth a shekel."
    else:
        answer = 'Ten for that? You must be mad!'
    

提交回复
热议问题