I wonder if it is bad manner to skip return None
, when it is not needed.
Example:
def foo1(x): if [some condition]: return Baz(x) else: return None def foo2(x): if [some condition]: return Baz(x) bar1 = foo1(x) bar2 = foo2(x)
In both cases, when condition is false, function will return with None
.
Like you said, return None is (almost) never needed. But you should consider that the intention of your code is much clearer with an explicit return None . Remember: a piece of code also needs to be readable by human-beings, and being explicit usually helps. "Explicit is better than implicit."
If your function performs actions but doesn't have a clear and useful return value, then you can omit returning None because doing that would just be superfluous and confusing. You can also use a bare return without a return value just to make clear your intention of returning from the function.
If we get to the end of any function and we have not explicitly executed any return statement, Python automatically returns the value None. Some functions exists purely to perform actions rather than to calculate and return a result. Such functions are called procedures.
No, you don't have to return something for every function. It is optional and upto how you write your code logic.
Like you said, return None
is (almost) never needed.
But you should consider that the intention of your code is much clearer with an explicit return None
. Remember: a piece of code also needs to be readable by human-beings, and being explicit usually helps.
To expound on what others have said, I use a return None
if the function is supposed to return a value. In Python, all functions return a value, but often we write functions that only ever return None, because their return value is ignored. In some languages, these would be called procedures.
So if a function is supposed to return a value, then I make sure all code paths have a return, and that the return has a value, even if it is None.
If a function "doesn't" return a value, that is, if it is never called by someone using its return value, then it's ok to end without a return, and if I need to return early, I use the bare form, return
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With