Python 用PEP8在操作员处断线?
如果我有一个带运算符的长表达式:Python 用PEP8在操作员处断线?,python,pep8,Python,Pep8,如果我有一个带运算符的长表达式: if (this_is_a_really_long_expression > this_is_a_really_really_long_expression): if (this_is_a_really_long_expression > this_is_a_really_really_long_expression): 我如何打破界限,使其符合PEP8 如果我在操作员之后将其断开: if (this_is_a_really_long_
if (this_is_a_really_long_expression > this_is_a_really_really_long_expression):
if (this_is_a_really_long_expression >
this_is_a_really_really_long_expression):
我如何打破界限,使其符合PEP8
如果我在操作员之后将其断开:
if (this_is_a_really_long_expression > this_is_a_really_really_long_expression):
if (this_is_a_really_long_expression >
this_is_a_really_really_long_expression):
Atom(我的编辑器)出于某种原因给出了一个语法错误…PEP8 now(自2016-06-08起):
几十年来,推荐的风格是在二进制运算符之后中断。但这会从两个方面影响可读性:运算符往往分散在屏幕上的不同列上,并且每个运算符都会从其操作数移到上一行。在这里,眼睛必须做额外的工作来辨别哪些项目被增加,哪些项目被减少:
# No: operators sit far away from their operands
income = (gross_wages +
taxable_interest +
(dividends - qualified_dividends) -
ira_deduction -
student_loan_interest)
为了解决这个可读性问题,数学家和他们的出版商遵循相反的惯例。Donald Knuth在他的计算机和排版系列中解释了传统规则:“尽管段落中的公式总是在二进制运算和关系之后中断,但显示的公式总是在二进制运算之前中断”[3]
遵循数学的传统通常会产生更可读的代码:
# Yes: easy to match operators with operands
income = (gross_wages
+ taxable_interest
+ (dividends - qualified_dividends)
- ira_deduction
- student_loan_interest)
具体而言,在这种情况下,备选方案是:
# No: last two lines have the same indentation
if (this_is_a_really_long_expression >
this_is_a_really_really_long_expression):
something_with_same_indentation()
# No: slightly better, but still last two lines have same indent
if (this_is_a_really_long_expression
> this_is_a_really_really_long_expression):
something_with_same_indentation()
# Yes (historically): easy to see it's not the next block
if (this_is_a_really_long_expression >
this_is_a_really_really_long_expression):
something_else()
# Yes: easy to see it's not the next block and what binary operator it is
if (this_is_a_really_long_expression
> this_is_a_really_really_long_expression):
something_else()
就个人而言,我非常喜欢后者,但是值得一提的是,目前仍然输出第三个(尽管我认为/尚未实现)
Linter(包括Atom!)将在头两行发出警告,E129视觉缩进行的缩进与下一逻辑行的缩进相同
Atom(我的编辑器)由于某种原因出现语法错误
我测试了Atom(它工作正常),它不是一个语法错误,但您的设置可能有问题。Atom是我使用的编辑器,Atom错误地认为它是一个语法错误。根据PEP8,您打断它的方式是可以接受的,但它表明在运算符之前打断它会更好(因为更可读),所以这是下一行的第一件事,比如@Tatsuya Yokota的答案没有反斜杠。这真的是语法错误吗,或者只是建议你不要在这里破折号?你能发布实际的代码吗?如前所述,这看起来像是有效的python语法,但表达式中可能存在一些错误。