Jim*_*ket 44 python coding-style pep8 line-breaks
我有一些像这样的代码.中断之前或之后是否应该中断?
# before
my_var = somethinglikethis.where(we=do_things).where(we=domore).where(we=everdomore)
# this way
my_var = somethinglikethis.where(we=do_things) \
.where(we=domore) \
.where(we=everdomore)
# or this way
my_var = somethinglikethis.where(we=do_things). \
where(we=domore). \
where(we=everdomore)
Run Code Online (Sandbox Code Playgroud)
Bas*_*ard 63
PEP 8建议使用括号,以便您不需要\,并在二元运算符之前轻轻地建议分解,而不是在它们之后.因此,格式化代码的首选方法是这样的:
my_var = (somethinglikethis
.where(we=do_things)
.where(we=domore)
.where(we=everdomore))
Run Code Online (Sandbox Code Playgroud)
这两个相关的段落来自最大线长度部分:
包装长行的首选方法是在括号,括号和括号内使用Python隐含的行继续.通过将表达式包装在括号中,可以在多行中分割长行.这些应该优先使用反斜杠来继续行.
......以及整数应该在二元运算符之前或之后换行吗?部分:
如果在二元运算符之前或之后换行?
几十年来,推荐的风格是在二元运算符之后打破.但这会以两种方式损害可读性:运算符往往分散在屏幕上的不同列中,并且每个运算符都会从其操作数移到前一行.在这里,眼睛必须做额外的工作来分辨哪些项目被添加以及哪些项目被减去:
Run Code Online (Sandbox Code Playgroud)# No: operators sit far away from their operands income = (gross_wages + taxable_interest + (dividends - qualified_dividends) - ira_deduction - student_loan_interest)为了解决这个可读性问题,数学家和他们的出版商遵循相反的惯例.Donald Knuth在他的计算机和排版系列中解释了传统规则:"虽然段落中的公式总是在二元操作和关系之后中断,但显示的公式总是在二元操作之前中断"
遵循数学传统通常会产生更易读的代码:
Run Code Online (Sandbox Code Playgroud)# Yes: easy to match operators with operands income = (gross_wages + taxable_interest + (dividends - qualified_dividends) - ira_deduction - student_loan_interest)在Python代码中,只要约定在本地一致,就允许在二元运算符之前或之后中断.对于新代码,建议使用Knuth的样式.
请注意,正如上面的引文所示,PEP 8 用于提供关于在哪里打破运营商的相反建议,下面引用后代:
包装长行的首选方法是在括号,括号和括号内使用Python隐含的行继续.通过将表达式包装在括号中,可以在多行中分割长行.这些应该优先使用反斜杠来继续行.确保适当缩进续行.打破二元运算符的首选位置是运算符之后,而不是它之前.一些例子:
Run Code Online (Sandbox Code Playgroud)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)
PEP 8 说在操作员之前打破是首选:
Donald Knuth 在他的 Computers and Typesetting 系列中解释了传统规则:“虽然段落中的公式总是在二元运算和关系之后中断,但显示的公式总是在二元运算之前中断”。
...
在 Python 代码中,只要约定在本地保持一致,就可以在二元运算符之前或之后中断。对于新代码,建议使用 Knuth 的样式。
https://www.python.org/dev/peps/pep-0008/#should-a-line-break-before-or-after-a-binary-operator
| 归档时间: |
|
| 查看次数: |
29979 次 |
| 最近记录: |