In programming, there are times when you want to explicitly indicate that a variable “has not been set yet” or “relevant data does not exist.” Python provides a special object called None for this purpose, which corresponds to null or nil in other languages.
This article explains the basic usage of None and the correct way to check if a value is None.
What is None?
None is the only value belonging to the NoneType data type. It is clearly distinct from 0 (zero), False (boolean false), or "" (empty string). None is a singleton object (meaning only one exists in the entire program) that represents the absence of a valid value.
Assigning None
None is often used as an initial value for variables or as a return value for functions.
# 1. Variable Initialization
# Initialize a variable with None, intending to set it later
user_config = None
# ... some processing ...
# Set value based on condition
if user_config is None:
print("Settings not loaded. Using default values.")
user_config = {"theme": "light", "lang": "ja"}
print(f"Config: {user_config}")
Output:
Settings not loaded. Using default values.
Config: {'theme': 'light', 'lang': 'ja'}
How to Check for None: Use is, not ==
When checking if a variable is None, Python’s official style guide (PEP 8) strongly recommends using the is operator (identity operator) instead of == (equality operator).
val == None(Not Recommended): Compares if the values are equal.val is None(Recommended): Compares ifvalandNoneare the exact same object in memory.
Since None is a singleton object, using is is faster and more reliable.
# Variable to check
received_data = None
item_count = 0
# 1. Good Example (Using 'is')
if received_data is None:
print("[is] Data not received (None).")
if item_count is not None:
print(f"[is not] Item count is {item_count} (Not None).")
print("-" * 20)
# 2. Bad Example (Using '==')
# It looks like it works, but should be avoided.
if received_data == None:
print("[==] Data not received (None).")
if item_count != None:
print(f"[!=] Item count is {item_count} (Not None).")
Output:
[is] Data not received (None).
[is not] Item count is 0 (Not None).
--------------------
[==] Data not received (None).
[!=] Item count is 0 (Not None).
Why use is? Some special objects might define their own rules for == (overriding the operator), which could cause == None to behave unexpectedly. is checks for object identity, so it is always safe and unaffected by such definitions.
Practical Example: Function Return Value
None is frequently used to indicate that a function “succeeded but has nothing to return” or “failed to find the item.”
def find_user_by_id(user_id, user_database):
"""
Search for a user in the database (dictionary) by ID.
Returns the user info (dict) if found, otherwise returns None.
"""
return user_database.get(user_id) # .get() returns None if key is missing
# --- Execution ---
users = {
"A001": {"name": "Sato", "age": 30},
"A002": {"name": "Suzuki", "age": 45},
}
# 1. When user is found
found_user_1 = find_user_by_id("A001", users)
if found_user_1 is not None:
print(f"ID A001 Name: {found_user_1['name']}")
else:
print("ID A001 User not found.")
# 2. When user is NOT found
found_user_2 = find_user_by_id("X999", users)
if found_user_2 is not None:
print(f"ID X999 Name: {found_user_2['name']}")
else:
print("ID X999 User not found.")
Output:
ID A001 Name: Sato
ID X999 User not found.
Summary
None is a crucial object in Python for indicating that a value does not exist.
- It is used for variable initialization and as a return value when no data exists.
- It is different from
0,False, or an empty string"". - Always use
isoris notto check forNone, not==.
