Last updated: Apr 8, 2024
Reading timeยท4 min
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.
# ๐๏ธ 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
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.
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.
# ๐๏ธ 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
The code sample first checks if the variable is not None
, in which case it
returns it.
Otherwise, a default value is returned.
An alternative approach is to use the boolean OR operator.
# ๐๏ธ 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"
The expression x or y
returns the value to the left if it's truthy, otherwise,
the value to the right is returned.
# ๐๏ธ default value print(None or 'default value') # ๐๏ธ hello print('hello' or 'default value')
However, this approach does not explicitly check for None
.
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:
None
and False
.0
(zero) of any numeric type""
(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.
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.
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.
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))
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.
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.
None
values for non-primitive parameters like lists and dictionaries.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.
def get_address(address={}): return address addr1 = get_address() addr2 = get_address() addr1['country'] = 'Chile' print(addr1) # ๐๏ธ {'country': 'Chile'} print(addr2) # ๐๏ธ {'country': 'Chile'}
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.
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.
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) # ๐๏ธ {}
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.
You can learn more about the related topics by checking out the following tutorials: