Is it ok to skip "return None"?

PythonFunctionReturn Value

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

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.

Solution 3 - Python

Yes and No.

In the simplest case, it is ok to skip "return None" because it returns None in only single negative condition.

But if there are nested condition evaluation and multiple scenarios where a function could return None. I tend to include them as visual documentation of the scenarios.

[Editing: Based on comment below]

> return or return None

I prefer "return None" to bare "return" as It is explicit and later, no one will be in doubt if the return meant returning None or was it an error as something was missing.

Solution 4 - Python

Yes, if you do not return any value from a Python function, it returns None. So, whether to explicitly return None is a stylistic decision.

Personally, I prefer to always return a value for clarity.

Solution 5 - Python

The more I think about it, the less I think the case you describe shows good practice. It forces the client to discriminate, so client code would almost always look like:

b = foo1(123)
if b is not None:
    ...

You couldn't even write:

if b:
    ...

since, if Baz.__nonzero__ is overwritten, b could evaluate to False, even if it's not None. It would be better to have a Null-Baz instance (AKA Null Object), e.g.:

class Baz(object):
    def some_method(self):
        """some action:"""
        ...
    ...

class BazNull(Baz):
    def some_method(self):
        """nothing happens here"""
    ...

Baz.Null = BazNull()

...

def foo1(x):
    if some_condition:
        return Baz(x)
    else:
        return Baz.Null

...

b = foo1(123)
b.some_method()

The point is: help the client (who might be yourself!) to keep Cyclomatic Complexity low. The fewer branches, the better.

Solution 6 - Python

def foo1(x):
    try:
        return Baz(x)
    except:
        raise ValueError('Incorrect value fo Bac')

or

def foo3(x):
    return Baz(x) if <condition> else False

I do not believe in half defined function, but this False can be usefull in search type failure pruning.

Solution 7 - Python

I disagree with a lot of the answers here.
Explicit is better than implicit but sometimes less is more when it comes to readability.

def get_cat():
    if cat_is_alive():
        return Cat()
# vs     

def get_cat():
    if cat_is_alive():
        return Cat()
    return None

In this particular example you have 2 extra lines that really provide no beneficial information since all functions return None by default.

Additionally explicitness of return None disappears even more with the usage of type hints:

def get_cat() -> Union[Cat, None]:
    if cat_is_alive():
        return Cat()

Including return None here is a double redundancy: None is returned by default and it's indicated explicitly in the type hint markup.

Imho avoid trailing return None they are absolutely pointless and ugly.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTomasz WysockiView Question on Stackoverflow
Solution 1 - PythonrsennaView Answer on Stackoverflow
Solution 2 - PythonNed BatchelderView Answer on Stackoverflow
Solution 3 - PythonpyfuncView Answer on Stackoverflow
Solution 4 - PythonJALView Answer on Stackoverflow
Solution 5 - PythonpillmuncherView Answer on Stackoverflow
Solution 6 - PythonTony VeijalainenView Answer on Stackoverflow
Solution 7 - PythonGranitosaurusView Answer on Stackoverflow