Why Returning None Is Bad and Better Ways to Handle Missing Values in Python
Returning None for missing data can cause unexpected crashes, so this article explains why that approach is problematic and demonstrates safer alternatives in Python, such as using default values with dict.get, raising exceptions when appropriate, and employing result objects to clearly indicate success or failure.
Previously I used to return None for missing values, but that can cause unexpected errors and make debugging difficult.
<code>user_data = {"name": "Kiran", "age": 25}
def get_email(user):
return user.get("email")
e = get_email(user_data)
print(e.upper())
</code>The program crashes because e is None ; we need to add a check like if e is not None .
1. Try using default values
If a value is missing, return a default.
Don’t do this:
<code>def get_username(user):
if 'name' in user:
return user['name']
return None
</code>Instead, do this:
<code>def get_username(user):
return user.get('name', "Guest")
</code>This returns a default value ("Guest") so the program won’t crash; use defaults only when they make sense, otherwise raise an exception.
5. Use result pattern
For functions that may fail, return a structured result instead of None .
<code>from typing import NamedTuple, Union
class Result(NamedTuple):
success: bool
value: Union[str, None]
def get_country(user) -> Result:
if 'country' in user:
return Result(True, user['country'])
return Result(False, None)
result = get_country({})
if not result.success:
print("Country not found!")
</code>This pattern makes it explicit whether the function succeeded.
Code Mala Tang
Read source code together, write articles together, and enjoy spicy hot pot together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.