Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it ok to skip "return None"?

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 image 712
Tomasz Wysocki Avatar asked Oct 26 '10 20:10

Tomasz Wysocki


People also ask

Is return None necessary?

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."

Is it good practice to return None in Python?

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.

What does it mean when a function returns None?

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.

Is it mandatory to return something from a function?

No, you don't have to return something for every function. It is optional and upto how you write your code logic.


2 Answers

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.

like image 188
rsenna Avatar answered Oct 02 '22 05:10

rsenna


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.

like image 34
Ned Batchelder Avatar answered Oct 02 '22 03:10

Ned Batchelder