Is it ok to skip “return None”?

后端 未结 7 1651
Happy的楠姐
Happy的楠姐 2020-12-03 06:17

I wonder if it is bad manner to skip return None, when it is not needed.

Example:

def foo1(x):
    if [some condition]:
        return B         


        
7条回答
  •  借酒劲吻你
    2020-12-03 06:58

    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.

提交回复
热议问题