Reputation:
If I have a long expression with an operator:
if (this_is_a_really_long_expression > this_is_a_really_really_long_expression):
how do I break it the line so it adheres to PEP8?
if I break it after the operator:
if (this_is_a_really_long_expression >
this_is_a_really_really_long_expression):
Atom (my editor) gives a syntax error for some reason...
Upvotes: 2
Views: 5311
Reputation: 375925
PEP8 now (since 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)
Specifically in this case, the alternatives would be:
# 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()
Personally I strongly prefer the latter, however it's worth mentioning that at the moment yapf
still outputs the 3rd (though I think it's a bug/not yet implemented)!
Linters (including Atom's!) will warn on the first two with E129 visually indented line with same indent as next logical line
.
Atom (my editor) gives a syntax error for some reason...
I tested Atom (it worked), it's not a SyntaxError, but there may be something broken in your setup.
Upvotes: 4