return, return None, and no return at all?

后端 未结 5 746
时光取名叫无心
时光取名叫无心 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:23

    They each return the same singleton None -- There is no functional difference.

    I think that it is reasonably idiomatic to leave off the return statement unless you need it to break out of the function early (in which case a bare return is more common), or return something other than None. It also makes sense and seems to be idiomatic to write return None when it is in a function that has another path that returns something other than None. Writing return None out explicitly is a visual cue to the reader that there's another branch which returns something more interesting (and that calling code will probably need to handle both types of return values).

    Often in Python, functions which return None are used like void functions in C -- Their purpose is generally to operate on the input arguments in place (unless you're using global data (shudders)). Returning None usually makes it more explicit that the arguments were mutated. This makes it a little more clear why it makes sense to leave off the return statement from a "language conventions" standpoint.

    That said, if you're working in a code base that already has pre-set conventions around these things, I'd definitely follow suit to help the code base stay uniform...

提交回复
热议问题