来自PEP 8——Python 代码风格指南:
包装长行的首选方法是在括号、方括号和大括号内使用 Python 的隐含行继续。通过将表达式括在括号中,可以将长行分成多行。这些应该优先使用反斜杠来继续行。
反斜杠有时可能仍然合适。例如,长的、多个 with 语句不能使用隐式延续,所以反斜杠是可以接受的:
with open('/path/to/some/file/you/want/to/read') as file_1, \
open('/path/to/some/file/being/written', 'w') as file_2:
file_2.write(file_1.read())
另一种情况是断言语句。
确保适当缩进续行。打破二元运算符的首选位置是在运算符之后,而不是在它之前。一些例子:
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)file_2.write(file_1.read())
PEP8 现在推荐数学家及其出版商使用的相反约定(用于打破二元运算)以提高可读性。
Donald Knuth 在二元运算符之前打破的风格使运算符垂直对齐,从而在确定添加和减去哪些项目时减少了眼睛的工作量。
来自PEP8:应该在二元运算符之前还是之后换行?:
Donald Knuth 在他的计算机和排版系列中解释了传统规则:“虽然段落中的公式总是在二元运算和关系之后中断,但显示的公式总是在二元运算之前中断”[3]。
遵循数学的传统通常会产生更具可读性的代码:
# Yes: easy to match operators with operands
income = (gross_wages
+ taxable_interest
+ (dividends - qualified_dividends)
- ira_deduction
- student_loan_interest)
在 Python 代码中,允许在二元运算符之前或之后中断,只要约定在本地是一致的。对于新代码,建议使用 Knuth 的样式。
[3]:Donald Knuth 的 The TeXBook,第 195 和 196 页