如果我有一个带运算符的长表达式:
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):
Atom(我的编辑器)出于某种原因出现语法错误...
答案 0 :(得分:2)
PEP8现在(自2016-06-08起)recommends breaking before the binary operator:
几十年来,推荐的风格是在二元运算符之后打破。但这会以两种方式损害可读性:运算符往往分散在屏幕上的不同列中,并且每个运算符都从其操作数移到前一行。在这里,眼睛必须做额外的工作来分辨哪些项目被添加以及哪些项目被减去:
# 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()
我个人非常喜欢后者,但值得一提的是,yapf
目前仍然输出第3个(虽然我认为it's a bug /尚未实施)!
Linters(包括Atom' s)将在前两个E129 visually indented line with same indent as next logical line
发出警告。
Atom(我的编辑器)出于某种原因出现语法错误...
我测试过Atom(它有效),它不是SyntaxError,但是你的设置可能会出现问题。