Function: Return `None`
Python adds an implicit return None
statement to the end of any function. In other words, if a function doesn’t specify a return value, it returns None
by default.
This means you can replace return None statements with bare return statements or even leave them out completely and still get the same result. E.g.:
def foo1(value):
if value:
return value
else:
return None
def foo2(value):
"""Bare return statement implies `return None`"""
if value:
return value
else:
return
def foo3(value):
"""Missing return statement implies `return None`"""
if value:
return value
>>> type(foo1(0))
<class 'NoneType'>
>>> type(foo2(0))
<class 'NoneType'>
>>> type(foo3(0))
<class 'NoneType'>
Rule of thumb:
- If a function does NOT have a return value (other languages would call this a procedure), then leave out the
return
statement. - If a function does have a return value from a logical point of view, then you need to decide whether to use an im- plicit return or not.