How to Return a default value if None in Python

avatar
Borislav Hadzhiev

Last updated: Apr 8, 2024
4 min

banner

# Table of Contents

  1. Return a default value if None in Python
  2. Using None as a default argument in Python

# Return a default value if None in Python

Use a conditional expression to return a default value if None in Python.

The conditional expression will return the default value if the variable stores None, otherwise the variable is returned.

main.py
# ๐Ÿ‘‡๏ธ Return a default value if the variable is None def example(): my_var = None return "default value" if my_var is None else my_var print(example()) # ๐Ÿ‘‰๏ธ "default value" # --------------------------------------------- # ๐Ÿ‘‡๏ธ Return a default value if the variable is None my_var = None my_var = "default value" if my_var is None else my_var print(my_var) # ๐Ÿ‘‰๏ธ default value

return default value if none

The code for this article is available on GitHub

Conditional expressions are very similar to an if/else statement.

In the examples, we check if the variable stores None, and if it does, we return the string default value, otherwise, the variable is returned.

You can use this approach to return a default value if None from a function or to reassign a variable to a default value if it currently stores None.

Alternatively, you can switch the order of conditions.

main.py
# ๐Ÿ‘‡๏ธ Return a default value if the variable is None def example(): my_var = None return my_var if my_var is not None else 'default value' print(example()) # ๐Ÿ‘‰๏ธ "default value" # --------------------------------------------- # ๐Ÿ‘‡๏ธ Return a default value if the variable is None my_var = None my_var = my_var if my_var is not None else 'default value' print(my_var) # ๐Ÿ‘‰๏ธ default value

switching the order of conditions

The code for this article is available on GitHub

The code sample first checks if the variable is not None, in which case it returns it.

Otherwise, a default value is returned.

# Return a default value if None using the boolean OR operator

An alternative approach is to use the boolean OR operator.

main.py
# ๐Ÿ‘‡๏ธ Return a default value if the variable is None def example(): my_var = None return my_var or "default value" print(example()) # ๐Ÿ‘‰๏ธ "default value" # --------------------------------------------- # ๐Ÿ‘‡๏ธ Return a default value if the variable is None my_var = None my_var = my_var or "default value" print(my_var) # ๐Ÿ‘‰๏ธ "default value"

return default value if none using boolean or

The code for this article is available on GitHub

The expression x or y returns the value to the left if it's truthy, otherwise, the value to the right is returned.

main.py
# ๐Ÿ‘‡๏ธ default value print(None or 'default value') # ๐Ÿ‘‡๏ธ hello print('hello' or 'default value')

However, this approach does not explicitly check for None.

The boolean or operator will return the value to the right if the value to the left is falsy.

All values that are not truthy are considered falsy. The falsy values in Python are:

  • constants defined to be falsy: None and False.
  • 0 (zero) of any numeric type
  • empty sequences and collections: "" (empty string), () (empty tuple), [] (empty list), {} (empty dictionary), set() (empty set), range(0) (empty range).

So if the value to the left is any of the aforementioned falsy values, the value to the right is returned.

main.py
print(0 or 'default value') # ๐Ÿ‘‰๏ธ default value print("" or 'default value') # ๐Ÿ‘‰๏ธ default value

This might or might not suit your use case.

If you only want to check for None, use the conditional expression from the first code snippet.

# Using None as a default argument in Python

None is often used as a default argument value in Python because it allows us to call the function without providing a value for an argument that isn't required on each function invocation.

None is especially useful for list and dict arguments.

main.py
def get_employee(name=None, age=None): return {'name': name, 'age': age} # ๐Ÿ‘‡ {'name': None, 'age': None} print(get_employee()) # ๐Ÿ‘‡๏ธ {'name': None, 'age': 30} print(get_employee(age=30)) # ๐Ÿ‘‡๏ธ {'name': 'Bobby Hadz', 'age': 30} print(get_employee('Bobby Hadz', 30))

using none as default argument

The code for this article is available on GitHub

We declared a function with 2 default parameters set to None.

Default parameter values have the form parameter = expression.

When we declare a function with one or more default parameter values, the corresponding arguments can be omitted when the function is invoked.

Note that positional parameters cannot follow a parameter with a default value because otherwise, Python has no way of knowing if we passed an argument for the default parameter or for a positional one.

A None value is often used for default parameters that are not essential to the function.

None is used when the function can still run even if a value for the parameter wasn't provided.

It's a best practice to use None values for non-primitive parameters like lists and dictionaries.

# Use None as default arguments, not Objects

Here is an example of how using an empty dictionary as a default value for a parameter can cause issues and how we can fix it with a None value.

main.py
def get_address(address={}): return address addr1 = get_address() addr2 = get_address() addr1['country'] = 'Chile' print(addr1) # ๐Ÿ‘‰๏ธ {'country': 'Chile'} print(addr2) # ๐Ÿ‘‰๏ธ {'country': 'Chile'}
The code for this article is available on GitHub

The get_address function has a parameter with a default value of an empty dictionary.

We called the function 2 times and stored the results in variables.

Notice that we only set the country key on one of the dictionaries but both of them got updated.

This is because default parameter values are only evaluated once - when the function is defined.

They are not evaluated each time the function is called.

When a non-primitive default parameter value, such as a dictionary or a list is mutated, it is mutated for all function calls.

To resolve the issue, set the default parameter value to None and conditionally update it in the body of the function.

main.py
def get_address(address=None): if address is None: address = {} return address addr1 = get_address() addr2 = get_address() addr1['country'] = 'Chile' print(addr1) # ๐Ÿ‘‰๏ธ {'country': 'Chile'} print(addr2) # ๐Ÿ‘‰๏ธ {}

using none as default argument value

The code for this article is available on GitHub

The body of the function is run every time it is invoked, so the issue is resolved.

I've also written an article on how to return multiple values and only use one.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev