return on negative condition vs if block [closed]
Asked Answered
E

0

7

If I have a function which should perform an action on some condition, and returns null instead, which is cleaner:

def func():
    if not condition:
        return None

    [...]
    return asd

or

def func():
    if condition:
        [...]
        value = asd
    else:
        value = None

    return value

I've read the paradigm that every function should have one returning point. On the other hand the zen of python says that flat is better than nested and later version adds one nested level above the whole action code ( marked as [...]).

Please also bear in mind that conditions could be more complicated and for example, add more than one nesting level.

Excitor answered 2/11, 2012 at 11:44 Comment(8)
It's perfectly fine to have multiple return points. Actually most of the times it's harder to see with what value a variable ended up with, when you have one final return point.Prouty
I agree with rantanplan. Having more than one return point is not bad. Having 23 return points is probably bad, but if you have just 2 of them there is no problem.Participate
It's all about readability, here, having the two return points is clearer than the extra if. It is worth noting, however, that if condition is any kind of error, you'd be better off raising an exception instead of returning None.Royer
I started to write an answer, but the question got closed before I could submit it. I'll paste it to the comment.Louque
There are some insights here also #37207Hackney
Forget about the single-return-point rule, it's made for languages like C that lack the equivalent of destructors or with/finally cleanup handlers. As for whether to return early or use else, it's a judgment call. If the branches are "balanced" and equally likely to occur, I prefer else. If the condition is exceptional and occurs early, it is better to use return, so that the casual reader can concentrate on the non-exceptional case.Louque
In this case 2 returning points help readability. And in a case like that, having the extra return you are being clear on what condition would stop the function execution.Debroahdebs
First of all, I think it is a valid question, should not be closed. But anyways, In my opinion second approach is better. Because having many return statements means exit points for the method, which compared to a single exit point, is harder to keep track of. Specially, if the method is doing complex things.Mord

© 2022 - 2024 — McMap. All rights reserved.