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?)
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:This is better as you often end up checking several errors in similar fashion in a sequence:
However, if your function instead branches to two equal branches, it could semantically make more sense to you else:
This is because you often end up adding several other options with
elif:To summarize: think about the semantics of your code and choose syntax accordingly.