Return Related Tips

Learn how to use return statements more efficiently in Python.

A function is a unit of computation. It’s a tool that we design and sharpen for a specific operation. It can also be reused, both by us and other programmers. Better functions improve the modularity, clarity, and maintainability of the program and increase its value overall. Our program is only as effective as its functions.

In many aspects, Python functions are similar to functions in other popular languages. They take parameters, perform computations, and return computed values to the caller, though there are some differences.

We must use functions in any program longer than a dozen lines.

In this chapter, we’ll learn to use the specific Pythonic function design mechanisms:

  • Multiple returns
  • Optional and keyword parameters generators
  • Anonymous functions
  • Functions creating functions

Make functions always return something

C, C++, Java, and even Fortran either allow functions to return exactly one result or none at all (void functions), while Python requires that every function return precisely one value. If our function doesn’t have a return statement at the end or has a return statement without a value, the function returns None. This function, for example, returns None:

Press + to interact
def aFuncThatReturnsNone():
a=1
aFuncThatReturnsNone() # Nothing displayed
print(aFuncThatReturnsNone())

If a function has a return statement with one value, that value is returned.

Return consistently

It is Pythonic to ensure that a function always returns the value of the same type.

The absence of function prototypes in Python makes it possible to design functions that return different data types, even when called with the arguments of the same data type. Consider the re.search() function for regular expression pattern matching. It returns an _sre.SRE_Match object on success and “nothing”:

Press + to interact
print(re.search('0', 'hello')) # Prints nothing
print(re.search('o', 'hello'))

Thankfully, None has the boolean value of False, so we can decide whether we can use the returned object for further processing:

match = re.search(pattern, 'hello') 
if match:
 
...