Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the recommended way to break long if statement? (W504 line break after binary operator)

What is currently the recommended way to break a long line of if statement with "and" and "or" operators?

1st option

With the style below (which is from PEP8) with flake8 I'm getting warnings: W504 line break after binary operator:

if (this_is_one_thing and     that_is_another_thing):     do_something() 

2nd option

if (this_is_one_thing     and that_is_another_thing):     do_something() 

Now I'm getting the warning W503 line break before the binary operator. The second seems to be in line with this recommendation from PEP8

I tried to find an answer but I'm still unsure. I think maybe using 2nd option and disabling the W503 warning will be a way to deal with this problem?

like image 630
ann.piv Avatar asked Jul 17 '19 10:07

ann.piv


People also ask

Should a line break before or after a binary operator?

Line breaks should occur before the binary operator to keep all operators aligned. This rule was changed on April 16th, 2016 in this commit. The tool is updated to recommend that line breaks should occur before the binary operator because it keeps all operators aligned.

Should a line break before or after a binary operator in Python?

In Python code, it is permissible to break before or after a binary operator, as long as the convention is consistent locally.


1 Answers

If we consult the documentation on flake 8 we see:

Anti-pattern

Note: Despite being in the anti-pattern section, this will soon be considered the best practice.

income = (gross_wages           + taxable_interest)

Best practice

Note: Despite being in the best practice section, this will soon be considered an anti-pattern.

income = (gross_wages +           taxable_interest)

So the line break before the binary operator will be considered best practice.

The documentation for W504, advices the operator before the new line as best practice, without the given note:

Anti-pattern

income = (gross_wages +           taxable_interest)

Best practice

income = (gross_wages           + taxable_interest)
like image 120
Willem Van Onsem Avatar answered Oct 19 '22 17:10

Willem Van Onsem