Pycodestyle: W503 enforces breaking after binary operators but PEP-8 appears to disagree

Created on 27 May 2016  路  4Comments  路  Source: PyCQA/pycodestyle

Straight from PEP-8:

Should a line break before or after a 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)

In Python code, it is permissible to break before or after a binary operator, as long as the convention is consistent locally. For new code Knuth's style is suggested.

Considering that the last paragraph allows breaking before or after binary operators, it seems like this should be handled similar to the --hang-indent option.

Most helpful comment

I initially searched for "W503", but that's found nothing relevant. After filing the ticket, I kept searching for binary operator and that came up with the other results. If nothing else this will be a useful result for others who do a similar search.

All 4 comments

It looks like this was also previously discussed in #197 and #498.

Exactly. This was discussed in #498 and has been addressed in two parts. In the future, please search open and closed issues before hand. ;-)

I initially searched for "W503", but that's found nothing relevant. After filing the ticket, I kept searching for binary operator and that came up with the other results. If nothing else this will be a useful result for others who do a similar search.

Also https://github.com/PyCQA/pycodestyle/issues/504 was opened about this with an even less searchable title and body. ;-)

Was this page helpful?
0 / 5 - 0 ratings