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

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

    PEP8 says the preferred way of breaking long lines is using parentheses:

    The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.

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

提交回复
热议问题