Reputation: 6296
Very simple question:
Specifically in Python (since Python actually has "strongly recommended" style guidelines specified in PEP 8, but really this applies to any language), should a function with an if
clause that always returns have the alternative code in an else
clause or not? In other words, func_style_one()
and func_style_two()
in the following piece of code are (obviously) exactly equivalent:
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()
Obviously, the best and most readable style depends on the situation, and opinions will vary greatly on which is better, but I'm asking which is specifically preferred by the core Python community. (e.g. Which is used more often in the standard library, all other things being equal?)
Upvotes: 7
Views: 248
Reputation: 30481
As a rule of thumb, you should always avoid adding unneccessary complexity to your code, whatever the language. It also often is a good idea to try to split your code into semantically meaninful subsections.
Given these heuristics, there is no definitive answer. It really boils down to what you are trying to achieve.
I'll demonstrate this with examples.
If we have a function that checks for various error conditions before proceeding, it could make sense to write it without else
:
def do_stuff():
if error1():
return cleanup_and_fail()
return ok()
This is better as you often end up checking several errors in similar fashion in a sequence:
def do_stuff():
if error1():
return cleanup_and_fail()
if error2():
return do_different_cleanup_and_fail()
return ok()
However, if your function instead branches to two equal branches, it could semantically make more sense to you else:
def do_stuff():
if option1():
return do_option1()
else:
return do_option2()
This is because you often end up adding several other options with elif
:
def do_stuff():
if option1():
return do_option1()
elif:
return do_option2()
else:
return do_option3()
To summarize: think about the semantics of your code and choose syntax accordingly.
Upvotes: 3