如果我有一个带有运算符的长表达式:
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(我的编辑器)由于某种原因给出了语法错误......
最佳答案
现在 PEP8(自 2016-06-08 起)recommends breaking before the 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:
# No: operators sit far away from their operands 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" [3].
Following the tradition from mathematics usually results in more readable code:
# 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
仍然输出第三个(尽管我认为 it's a bug/尚未实现)!
Linter(包括 Atom 的!)将对前两个警告,并显示 E129 视觉缩进行,其缩进与下一个逻辑行相同
。
Atom (my editor) gives a syntax error for some reason...
我测试了 Atom(它有效),这不是语法错误,但您的设置中可能有问题。
关于python - 使用 PEP8 在运算符(operator)处断线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47244631/