在'if'语句中设置多行条件的样式? [英] Styling multi-line conditions in 'if' statements?
问题描述
有时我会在中将长条件分解为多行,如果
s。最明显的方法是:
Sometimes I break long conditions in if
s onto several lines. The most obvious way to do this is:
if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
视觉上不是很吸引人,因为动作与条件相融合。但是,这是使用4个空格的正确Python缩进的自然方式。
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.
目前我正在使用:
if ( cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
但这不是很漂亮。 : - )
But this isn't very pretty. :-)
你能推荐另一种方式吗?
Can you recommend an alternative way?
推荐答案
您不需要在第二个条件行上使用4个空格。也许使用:
You don't need to use 4 spaces on your second conditional line. Maybe use:
if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
此外,不要'忘记空格比你想象的更灵活:
Also, 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_something
但这两个都相当丑陋。
可能会丢失括号(样式指南虽然不鼓励这样做?
Maybe lose the brackets (the Style Guide discourages this though)?
if cond1 == 'val1' and cond2 == 'val2' and \
cond3 == 'val3' and cond4 == 'val4':
do_something
这至少可以让你有所区别。
This at least gives you some differentiation.
或者甚至:
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_something
这是样式指南,(自2010年起)建议使用括号。
Here's the Style Guide, which (since 2010) recommends using brackets.
这篇关于在'if'语句中设置多行条件的样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!