patternpythonCriticalCanonical
Styling multi-line conditions in 'if' statements?
Viewed 0 times
stylinglineconditionsstatementsmulti
Problem
Sometimes I break long conditions in
Isn't very very appealing visually, because the action blends with the conditions. However, it is the natural way using correct Python indentation of 4 spaces.
For the moment I'm using:
But this isn't very pretty. :-)
Can you recommend an alternative way?
ifs onto several lines. The most obvious way to do this is:if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_somethingIsn't very very appealing visually, because the action blends with the conditions. However, it is the natural way using correct Python indentation of 4 spaces.
For the moment I'm using:
if ( cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_somethingBut this isn't very pretty. :-)
Can you recommend an alternative way?
Solution
You don't need to use 4 spaces on your second conditional line. Maybe use:
Also, don't forget the whitespace is more flexible than you might think:
Both of those are fairly ugly though.
Maybe lose the brackets (the Style Guide discourages this though)?
This at least gives you some differentiation.
Or even:
I think I prefer:
Here's the Style Guide, which (since 2010) recommends using brackets.
if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_somethingAlso, don't forget the whitespace is more flexible than you might think:
if (
cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'
):
do_something
if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_somethingBoth of those are fairly ugly though.
Maybe lose the brackets (the Style Guide discourages this though)?
if cond1 == 'val1' and cond2 == 'val2' and \
cond3 == 'val3' and cond4 == 'val4':
do_somethingThis at least gives you some differentiation.
Or even:
if cond1 == 'val1' and cond2 == 'val2' and \
cond3 == 'val3' and \
cond4 == 'val4':
do_somethingI think I prefer:
if cond1 == 'val1' and \
cond2 == 'val2' and \
cond3 == 'val3' and \
cond4 == 'val4':
do_somethingHere's the Style Guide, which (since 2010) recommends using brackets.
Code Snippets
if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_somethingif (
cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'
):
do_something
if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_somethingif cond1 == 'val1' and cond2 == 'val2' and \
cond3 == 'val3' and cond4 == 'val4':
do_somethingif cond1 == 'val1' and cond2 == 'val2' and \
cond3 == 'val3' and \
cond4 == 'val4':
do_somethingif cond1 == 'val1' and \
cond2 == 'val2' and \
cond3 == 'val3' and \
cond4 == 'val4':
do_somethingContext
Stack Overflow Q#181530, score: 1025
Revisions (0)
No revisions yet.