wei*_*ler 4 python return indentation
我想知道是否有一种很好的方法可以告诉python解释器跳转到函数的下一个/最后一个return语句.
让我们假设以下虚拟代码:
def foo(bar):
do(stuff)
if condition:
do(stuff)
if condition2:
do(stuff)
if condition3:
...
return (...)
Run Code Online (Sandbox Code Playgroud)
有时候,由于它们依赖于上面的块do(stuff),因此很多条件无法链接.我现在可以这样做:
def foo(bar):
do(stuff)
if not condition: return (...)
do(stuff)
if not condition2: return (...)
do(stuff)
if not condition3: return (...)
...
return (...)
Run Code Online (Sandbox Code Playgroud)
它看起来有点不那么凌乱,但我不得不一次又一次地重复返回语句,这是一个很麻烦的东西,如果它是一个长元组或类似的甚至看起来更糟.完美的解决方案是说"如果没有条件,请跳到最终的退货声明".这有点可能吗?
编辑:明确这一点:我的目标是提高可读性,同时避免性能下降
我想我会创建一个函数列表(我假设do(stuff)你的例子中的所有函数实际上都是不同的函数).然后你可以使用for循环:
list_of_funcs = [func1, func2, func3]
for func in list_of_funcs:
func(stuff)
if not condition:
break
return (...)
Run Code Online (Sandbox Code Playgroud)
如果条件不同,那么您还可以创建条件列表(这将是返回的函数列表True或False),然后您可以zip按以下方式使用:
list_of_funcs = [func1, func2, func3]
list_of_conditions = [cond1, cond2, cond3]
for func, cond in zip(list_of_funcs, list_of_conditions):
func(stuff)
if not cond():
break
return (...)
Run Code Online (Sandbox Code Playgroud)
这样,无论您有多少功能和条件,您的实际代码都保持相同的长度和相同的缩进级别.