'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?
Solution 1:[1]
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)
Solution 2:[2]
When in doubt, ask Black:
if (
this_is_one_thing
and that_is_another_thing
):
do_something()
For a long time, PEP-8 recommended breaking after a binary operator, but they have "recently" switched to the Donald-Knuth-approved break-before-binary-operator style.
Solution 3:[3]
instead and
or or
you can use all
or any
:
if all(
this_is_one_thing,
that_is_another_thing):
do_something()
Solution 4:[4]
Flake8 is one of the Python lints, and the full list of errors can be found useful to find anti-patterns and best practices for each specific error.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | |
Solution 3 | vlk |
Solution 4 | FoxyFox |