Four ways to return a default value if None in Python
One of the most common tasks when working with variables in Python is to return a default value if a variable (or a dictionary item) is None
or if it doesn’t even exist.
This quick guide explores four methods of returning a default value if a variable is None
or doesn’t exist.
🎧 Debugging Jam
Calling all coders in need of a rhythm boost! Tune in to our 24/7 Lofi Coding Radio on YouTube, and let's code to the beat – subscribe for the ultimate coding groove!" Let the bug-hunting begin! 🎵💻🚀
How to return a default value if None
There are several ways to do to return a default value if a variable (or a dictionary item) is None
or if it doesn’t exist:
- Standard if statement
- One-liner if/else statement
- The get() method (only dictionaries)
- The try/except statement
Let’s explore each approach with examples.
1. Standard if statement: The simplest and most readable way of returning a default value – if a variable is None
– is to use a standard if
block.
Here’s how you’d do it:
def get_name():
return None
name = get_name()
# Set a default value if the name is None
if name is None:
name = 'User'
print(name)
# Output: User
In the above example, we have a function get_name()
, which is supposed to return a value to the caller. The function's returned value is stored in the name
variable. If the function returns None
, we set the name to User
.
This way, you won't need an else
block.
2. One-liner if/else statement: The previous method could be rewritten in one line. This is probably the most Pythonic way of doing this, even though it's less intuitive than a simple if
.
def get_name():
return 'some value'
name = 'User' if get_name() is None else get_name()
print(name)
# Output: some value
The above example works as it reads: set the name to 'User'
if get_name()
returns None
. Otherwise, use get_name()
return value.
3. Using or: If you're sure the returned value is either a string or None
, you can use the "value or 'default'"
syntax:
def get_name():
return None
name = get_name() or 'User'
print(name)
# Output: User
This syntax returns the lefthand side value if it's truthy. Otherwise, it'll return the value on the right.
Values that are equivalent to false (in if
and while
statements) in Python are:
- None
- 0
- False
- Any object that its
__len__()
method returns 0 (e.g., dictionaries, lists, tuples, empty strings, etc.)
Tip: You can also use this technique to return a default value for empty strings.
While this works well, you should be aware the above example still returns 'User'
if get_name()
returns one of the above "falsy" values. However, if you know the value is either a string or None
, it's an option you might want to consider.
3. The get() method (only dictionaries): You can use the get()
method of a dict
object and return a default value if a specific key doesn't exist.
Let's see an example:
person = {
'first_name': 'John',
'last_name': 'Smith',
'department': None
}
print(person.get('age', 'Not specified'))
# Output: Not specified
print(person.get('department', 'Not specified'))
# Output: None
As you can see, if the key exists but it's None
, it'll be returned. However, it might not be what you want.
To return a default value if the respective key is None
, you can do so:
person = {
'first_name': 'John',
'last_name': 'Smith',
'department': None
}
if 'department' not in person or person['department'] is None:
person['department'] = 'default value'
print(person['department'])
# Output: default value
You can also use a try/except
statement like so:
person = {
'first_name': 'John',
'last_name': 'Smith',
}
try: person['department']
except KeyError: person['department'] = 'default value'
print(person['department'])
# Output: default value
Or do it in two steps:
person = {
'first_name': 'John',
'last_name': 'Smith',
}
try: person['department']
except KeyError: person['department'] = None
if (person['department'] is None):
person['department'] = 'default value'
print(person['department'])
# Output: default value
4. The try/except statement: As mentioned earlier, you can use the try/except
statement to return a default value if a dictionary item is None
. This technique isn't limited to dictionaries, though.
You can use them for variables too. However, you must catch the NameError
exception this time.
try: name
except NameError: name = None
if name is None:
name = 'default value'
print(name)
# output: default value
The above snippet might seem redundant for many use cases. However, since Python doesn't have a function like isset()
in PHP, this is how you can make it up.
Alright, I think it does it! I hope you found this quick guide helpful.
Thanks for reading!
Never miss a guide like this!
Disclaimer: This post may contain affiliate links. I might receive a commission if a purchase is made. However, it doesn’t change the cost you’ll pay.