Dav*_*man 7 python coding-style
很简单的问题:
特别是在Python中(因为Python实际上具有在PEP 8中指定的"强烈推荐"样式指南,但实际上这适用于任何语言),具有if始终返回的子句的函数是否应该在子句中具有替代代码else?换句话说,func_style_one()和func_style_two()在下面的代码段是(明显)完全等效:
def func_style_one():
if some_conditional_function():
do_something()
return something()
else:
do_something_else()
return something_else()
def func_style_two():
if some_conditional_function():
do_something()
return something()
do_something_else()
return something_else()
Run Code Online (Sandbox Code Playgroud)
显然,最好和最具可读性的风格取决于具体情况,而且意见会有所不同,哪个更好,但我问的是核心Python社区特别偏好哪个.(例如,标准库中哪些更常用,所有其他条件相同?)
根据经验,无论使用哪种语言,您都应该始终避免为代码添加不必要的复杂性。尝试将代码分成语义上有意义的小节通常也是一个好主意。
鉴于这些启发,没有明确的答案。这实际上取决于您想要实现的目标。
我将用例子来证明这一点。
如果我们有一个在继续之前检查各种错误条件的函数,那么在不使用以下内容的情况下编写它可能是有意义的else:
def do_stuff():
if error1():
return cleanup_and_fail()
return ok()
Run Code Online (Sandbox Code Playgroud)
这更好,因为您经常最终会按顺序以类似的方式检查多个错误:
def do_stuff():
if error1():
return cleanup_and_fail()
if error2():
return do_different_cleanup_and_fail()
return ok()
Run Code Online (Sandbox Code Playgroud)
但是,如果您的函数改为分支到两个相等的分支,那么它在语义上对您来说可能更有意义:
def do_stuff():
if option1():
return do_option1()
else:
return do_option2()
Run Code Online (Sandbox Code Playgroud)
这是因为您经常最终添加几个其他选项elif:
def do_stuff():
if option1():
return do_option1()
elif:
return do_option2()
else:
return do_option3()
Run Code Online (Sandbox Code Playgroud)
总结一下:考虑代码的语义并相应地选择语法。