0

i was implementing merge sort and in the base case found that there is no diff btw empty return and return None.

if cond:
   return

and

if cond:
   return None

is there any diff or 2 are equivalent?

petezurich
  • 9,280
  • 9
  • 43
  • 57
ERJAN
  • 23,696
  • 23
  • 72
  • 146
  • 2
    They are equivalent. I tend to use an explicit `return None` if the function may return different types. – snakecharmerb Feb 29 '20 at 19:50
  • For the caller of the function - they are the same. But for anyone reading the code, it's a matter of explicit vs implicit. – rdas Feb 29 '20 at 19:51
  • There is also a difference in Python 2, if the function is a generator (i.e. has `yield` inside) - in that case `return` is a valid way to end the function whereas `return None` is not. – zvone Feb 29 '20 at 19:54
  • 2
    PEP recommends `return None` if any valid value is returned elsewhere in the function, otherwise `return` is fine. – Carcigenicate Feb 29 '20 at 19:54
  • "The `return` statement returns with a value from a function. `return` without an expression argument returns `None`. Falling off the end of a function also returns `None`." (from the [Official Python Tutorial](https://docs.python.org/3/tutorial/controlflow.html#defining-functions) – Jongware Feb 29 '20 at 19:57

1 Answers1

3

According to the doc, if no expression is given to return then None is substituted. So no there is no difference.

Edit:

Even with no return statement, a function returns None:

>>> def f():
...    print("do nothing")
...
>>> r=f()
do nothing
>>> r is None
True
rolf82
  • 1,531
  • 1
  • 5
  • 15