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

ann.piv picture ann.piv · Jul 17, 2019 · Viewed 9.7k times · Source

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?

Answer

Willem Van Onsem picture Willem Van Onsem · Jul 17, 2019

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)