有时我会将ifs中的长条件分成几行.最明显的方法是:
if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
Run Code Online (Sandbox Code Playgroud)
视觉上不是很吸引人,因为动作与条件相融合.但是,这是使用4个空格的正确Python缩进的自然方式.
目前我正在使用:
if ( cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
Run Code Online (Sandbox Code Playgroud)
但这不是很漂亮.:-)
你能推荐另一种方式吗?
根据PEP标准,缩进应该在二进制运算符之前。此外,多行条件应放在括号内,以避免在换行符前使用反斜杠。这两个约定导致以下情况
if (long_condition_1
or long_condition_2):
do_some_function()
Run Code Online (Sandbox Code Playgroud)
该代码反过来E129 visually indented line with same indent as next logical line在PEP8中中断。但是,第二行必须缩进四个空格,否则,对于缩进或缩进过的行,它会破坏E128或E127。
如何格式化上面的一种,使其符合PEP8标准?