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.

user1725145
  • 3,993
  • 2
  • 37
  • 58
yakxxx
  • 2,841
  • 2
  • 21
  • 22
  • 7
    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. – rantanplan Nov 02 '12 at 11:54
  • 2
    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. – Bakuriu Nov 02 '12 at 11:55
  • 1
    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``. – Gareth Latty Nov 02 '12 at 11:59
  • I started to write an answer, but the question got closed before I could submit it. I'll paste it to the comment. – user4815162342 Nov 02 '12 at 12:01
  • There are some insights here also http://stackoverflow.com/questions/36707/should-a-function-have-only-one-return-statement – Faruk Sahin Nov 02 '12 at 12:01
  • 4
    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. – user4815162342 Nov 02 '12 at 12:01
  • 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. – Ignacio Contreras Pinilla Nov 02 '12 at 12:02
  • 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. – Nazar Merza Nov 02 '12 at 16:28

0 Answers0