PEP 8建议使用括号,这样就不需要\
,并且温和地建议在二元运算符之前而不是之后进行断行。因此,格式化代码的首选方式如下:
my_var = (somethinglikethis
.where(we=do_things)
.where(we=domore)
.where(we=everdomore))
两个相关的段落是来自于
最大行长度部分的以下内容:
首选的换行方式是使用Python中括号、方括号和花括号内隐含的行连接。可以通过将表达式包装在括号中来将长行分成多行。这应该优先于使用反斜杠进行行连接。
... 和整个
二进制运算符前后是否应该换行?部分:
Should a line break before or after a binary operator?
For decades the recommended style was to break after binary operators.
But this can hurt readability in two ways: the operators tend to get
scattered across different columns on the screen, and each operator is
moved away from its operand and onto the previous line. Here, the eye
has to do extra work to tell which items are added and which are
subtracted:
income = (gross_wages +
taxable_interest +
(dividends - qualified_dividends) -
ira_deduction -
student_loan_interest)
To solve this readability problem, mathematicians and their publishers
follow the opposite convention. Donald Knuth explains the traditional
rule in his Computers and Typesetting series: "Although formulas
within a paragraph always break after binary operations and relations,
displayed formulas always break before binary operations"
Following the tradition from mathematics usually results in more
readable code:
income = (gross_wages
+ taxable_interest
+ (dividends - qualified_dividends)
- ira_deduction
- student_loan_interest)
In Python code, it is permissible to break before or after a binary
operator, as long as the convention is consistent locally. For new
code Knuth's style is suggested.
请注意,如上所述,PEP 8曾经在断开运算符周围的位置方面给出相反的建议,并为了记录而引用了以下内容:
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.
Make sure to indent the continued line appropriately. The preferred place
to break around a binary operator is after the operator, not before it.
Some examples:
class Rectangle(Blob):
def __init__(self, width, height,
color='black', emphasis=None, highlight=0):
if (width == 0 and height == 0 and
color == 'red' and emphasis == 'strong' or
highlight > 100):
raise ValueError("sorry, you lose")
if width == 0 and height == 0 and (color == 'red' or
emphasis is None):
raise ValueError("I don't think so -- values are %s, %s" %
(width, height))
Blob.__init__(self, width, height,
color, emphasis, highlight)
Rectangle
示例在2013年进行了更新,使用新的多行if缩进方式。(我曾尝试编辑答案,但并未成功。看这里。) - duozmo