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.
if
. It is worth noting, however, that ifcondition
is any kind of error, you'd be better off raising an exception instead of returningNone
. – Royerwith
/finally
cleanup handlers. As for whether toreturn
early or useelse
, it's a judgment call. If the branches are "balanced" and equally likely to occur, I preferelse
. If the condition is exceptional and occurs early, it is better to usereturn
, so that the casual reader can concentrate on the non-exceptional case. – Louquereturn
you are being clear on what condition would stop the function execution. – Debroahdebs