Prevent a function from returning None in Python

avatar

Borislav Hadzhiev

Last updated: Aug 24, 2022

banner

Photo from Unsplash

Prevent a function from returning None in Python #

To prevent a function from returning None in Python, make sure to return a value from the function. All functions that don't explicitly return a value return None in Python.

main.py
# 👇️ returns None def example(): print('hi there') result = example() print(result) # 👉️ None

We didn't explicitly return a value from the function, so it implicitly returns None.

Use the return statement to return a value from the function.

main.py
# 👇️ returns None def example(): return 'hi there' result = example() print(result) # 👉️ 'hi there'
Note that all functions that don't explicitly return a value, end up implicitly returning None.

The most common sources of None values are:

  1. Having a function that doesn't return anything (returns None implicitly).
  2. Explicitly setting a variable to None.
  3. Assigning a variable to the result of calling a built-in function that doesn't return anything.
  4. Having a function that only returns a value if a certain condition is met.
Note that there are many built-in functions (e.g. sort()) that mutate the original object in place and return None.
main.py
my_list = ['c', 'b', 'a'] result = my_list.sort() print(result) # 👉️ None

If the function mutates the original object, don't assign the result of calling it to a variable.

main.py
my_list = ['c', 'b', 'a'] my_list.sort() print(my_list) # 👉️ ['a', 'b', 'c']

Another common source of None values is having a function that returns a value only if a condition is met.

main.py
def get_list(a): if len(a) > 3: return a # 👇️ None my_list = get_list([1, 2]) print(my_list) # 👉️ None

The if statement in the get_list function is only run if the passed in argument has a length greater than 3.

In all other cases, the function doesn't return anything and ends up implicitly returning None.

To get around this, we could return a default value if the condition is not met, e.g. an empty string, an empty list, 0, or any other value that suits your use case.

main.py
def get_list(a): if len(a) > 3: return a return [] # 👈️ return empty list if condition not met # 👇️ [] my_list = get_list(['a', 'b']) print(my_list) # 👉️ []

Now the function is guaranteed to return a value regardless if the condition is met.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.