Python's preferred style (or any language, actually): should I use when it comes back?

A very simple question:

In particular, in Python (since Python actually has the “highly recommended” style rules specified in PEP 8 , but it really applies to any language) should a function with an if clause that always returns have alternative code in the clause else or not? In other words, func_style_one() and func_style_two() in the following code snippet 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 will depend on the situation, and opinions will differ greatly, which is better, but I ask what the core of the Python community prefers specifically. (for example, which is used more often in the standard library, all other things being equal?)

+7
source share
1 answer

As a rule of thumb, you should always avoid adding too much complexity to your code, regardless of language. It is also often nice to try breaking your code down into semantically meaningful sub-sections.

Given these heuristics, there is no final answer. It really comes down to what you are trying to achieve.

I will demonstrate this with examples.

If we have a function that checks various error conditions before continuing, it may make sense to write it without else :

 def do_stuff(): if error1(): return cleanup_and_fail() return ok() 

This is better because you often end up checking for multiple errors in a similar way in the 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 moves to two equal branches, it may semantically make more sense to you:

 def do_stuff(): if option1(): return do_option1() else: return do_option2() 

This is because you often add several other parameters 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 the syntax accordingly.

+3
source

All Articles