There is no requirement for an explicit return
– a Python function will implicitly return None
when it ends without a value.
>>> def void():
... a = 3 + 4
...
>>> print(void())
None
As for what is advisable, per the official style guide it is idiomatic to be consistent with return
statements:
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):
Note how an explicit return statement at the end of the function should only be used if the function may return some value other than the implied None
. There are basically three cases:
- The function
return
s never. Do not add return
at the end.
- The function
return
s early but without an explicit value. Do not add return
at the end.
- The function
return
s at least one explicit value. Do add return
with an explicit value at the end.
As an example, it would make sense for the function to signal success or failure:
def mytest():
return_code = os.system('convert ./text.pdf ./text.jpg')
# demonstration only – use `return return_code == 0` in practice
if return_code == 0:
return True # explicit return of a value
return False # -> explicit return at the end