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

后端 未结 3 949
逝去的感伤
逝去的感伤 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:44

    You can always extend a logical line across multiple physical lines with parentheses:

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

    This is called implicit line joining.

    The above uses the PEP8 everything-indented-one-step-more style (called a hanging indent). You can also indent extra lines to match the opening parenthesis:

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

    but this leaves you hitting the 80-column maximum all the faster.

    Where precisely you put the if and else portions is up to you; I used my personal preference above, but there is no specific style for the operator that anyone agrees on, yet.

提交回复
热议问题