Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
805 views
in Technique[技术] by (71.8m points)

python - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...