Which Python Conditional Return Statement Is The Most Pythonic?
The proper Python way would be:
return conditional
"Simple is better than complex" remember? :)
Regarding your edited question, I would use # OPTION 2
because "Flat is better than nested." and this solution saves an indentation level. You'll appreciate this when:
return b
is actually something like:
return very_long_and_unwieldy_name_that_you_cannot_change
Besides, the else:
in this case is unnecessary (both syntactically as well as visually) and redundant; it simply wastes space.
That said, you may want to 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 all nice and short.
I think this may be a trick question. The first one is not syntactically correct:
if conditional:
return True
else:
return False
In Python, an else
clause, like anything else that introduces a suite, has to end in a :
character.
If you fix that, then they're both syntactically valid, and both semantically meaningful. In fact, they mean the same thing. They'll even compile to almost the same code, except that the first one might cause Python to generate some extra code for a third "fall off the end of the function" case that never gets called.
But, as iCodez's answer explains, both of these are an anti-pattern; just return conditional
, or return bool(conditional)
, as appropriate.
Note that even in the case where evaluating conditional
raises an exception, the different possibilities are still all equivalent (up to the contents of the traceback)—they'll all just raise that exception.