return, return None, and no return at all?

后端 未结 5 640
时光取名叫无心
时光取名叫无心 2020-11-22 01:07

Consider three functions:

def my_func1():
  print \"Hello World\"
  return None

def my_func2():
  print \"Hello World         


        
5条回答
  •  忘了有多久
    2020-11-22 01:49

    As other have answered, the result is exactly the same, None is returned in all cases.

    The difference is stylistic, but please note that PEP8 requires the use to be consistent:

    Be consistent in return statements. Either all return statements in a function should return an expression, or none of them should. If any return statement returns an expression, any return statements where no value is returned should explicitly state this as return None, and an explicit return statement should be present at the end of the function (if reachable).

    Yes:

    def foo(x):
        if x >= 0:
            return math.sqrt(x)
        else:
            return None
    
    def bar(x):
        if x < 0:
            return None
        return math.sqrt(x)
    

    No:

    def foo(x):
        if x >= 0:
            return math.sqrt(x)
    
    def bar(x):
        if x < 0:
            return
        return math.sqrt(x)
    

    https://www.python.org/dev/peps/pep-0008/#programming-recommendations


    Basically, if you ever return non-None value in a function, it means the return value has meaning and is meant to be caught by callers. So when you return None, it must also be explicit, to convey None in this case has meaning, it is one of the possible return values.

    If you don't need return at all, you function basically works as a procedure instead of a function, so just don't include the return statement.

    If you are writing a procedure-like function and there is an opportunity to return earlier (i.e. you are already done at that point and don't need to execute the remaining of the function) you may use empty an returns to signal for the reader it is just an early finish of execution and the None value returned implicitly doesn't have any meaning and is not meant to be caught (the procedure-like function always returns None anyway).

提交回复
热议问题