Is it ok to skip "return None"?

Viewed 35835

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.

7 Answers

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.

Related