Is there a reason python functions should always return some value?

Viewed 501

When I started to code with python, a senior developer was advising me to put a return True (boolean value in general) whenever the scope of a function ends.

so for example:

def mytest():
    try:
        os.system('convert ./text.pdf ./text.jpg')
    except:
        pass
   
    return True

Still, does it matter to the python interpreter? Is returning None equivalent to not returning at all?

1 Answers

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 returns never. Do not add return at the end.
  • The function returns early but without an explicit value. Do not add return at the end.
  • The function returns 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
Related