Which Python conditional return statement is the most pythonic?

Which of the following is the correct way to return something with Python when using conditional expressions? Does it matter? And why?

# OPTION 1 if conditional: return a else: return b # OPTION 2 if conditional: return a return b 
+6
source share
2 answers

The correct Python way:

 return conditional 

"Simple is better than complex" remember? :)


As for your edited question, I would use # OPTION 2 because "Flat is better than nested." and this solution maintains the level of indentation. You will appreciate it when:

 return b 

actually something like:

 return very_long_and_unwieldy_name_that_you_cannot_change 

In addition, else: in this case is not necessary (both syntactically and visually) and redundant; he is just wasting space.

However, you might consider using a conditional expression instead:

 return a if conditional else b 

This is a very concise and elegant alternative when a , conditional and b are nice and short.

+12
source

I think this can be a moot point. The first one is not syntactically correct:

 if conditional: return True else return False 

In Python, the else clause, like everything that the set enters, must end with the character :

If you fix this, then they are both syntactically valid and both semantically significant. In fact, they mean the same thing. They even compile using almost the same code, except that the first can cause Python to generate additional code for the third case, "fall off the end", which is never called.

But, as iCodez explains, both of them are anti-patterns; just return conditional or return bool(conditional) if necessary.

Note that even if the conditional evaluation throws an exception, the different options are still equivalent (up to the contents of the trace) - they all just raise this exception.

0
source

Source: https://habr.com/ru/post/977686/


All Articles