Back to series
· 8 min read

Python None and Null Value Handling


I. Basic Concepts of None

None is a built-in special constant in Python, used to indicate that an object does not have a clear value, or that an operation did not return a meaningful result.

result = None

print(result)        # None
print(type(result))  # <class 'NoneType'>

None has the following characteristics:

  • None is a constant, not an ordinary variable aside from being a keyword.
  • The type of None is NoneType.
  • NoneType has only one instance, namely None.
  • None is an immutable object.
  • None is false in Boolean contexts.
  • None is often used to represent missing values, no return value, and optional states.

1. The NoneType Type

In Python, you can use type() to check the type of None:

print(type(None))
# <class 'NoneType'>

You can also use an isinstance check:

value = None

print(isinstance(value, type(None)))  # True

Although you can obtain NoneType via type(None), everyday business code usually does not need to reference this type directly.

2. None Is a Singleton Object

None in Python is a singleton, and there is usually only one None object in the entire interpreter process.

a = None
b = None

print(a is b)  # True

Therefore, to determine whether a variable is None, you should use the identity operator is:

if value is None:
    print("没有值")

Reverse check:

if value is not None:
    print("存在值")

Not recommended:

if value == None:
    print("没有值")

The reason is that == invokes the object's equality comparison logic, and custom objects can override __eq__(), whereas is checks object identity and is not affected by equality overloading.

II. Common Use Cases for None

1. Indicating That a Function Has No Return Result

If a Python function does not explicitly execute return, it returns None by default.

def print_message():
    print("Hello Python")


result = print_message()

print(result)  # None

The following two forms are equivalent:

def func_a():
    pass


def func_b():
    return None

Explicitly returning None can make the function's return semantics clearer.

2. Representing Optional Parameters

Function parameters can use None to indicate that the caller did not provide a value.

def connect(host, port=None):
    if port is None:
        port = 8080

    print(host, port)


connect("localhost")
connect("localhost", 9000)

This design is suitable when a parameter genuinely has optional semantics.

3. Representing Not Yet Initialized

During the lifecycle of an object or variable, None can indicate that actual data has not yet been obtained.

user = None

def load_user():
    global user
    user = {"id": 1, "name": "Alice"}


print(user)  # None

load_user()

print(user)  # {'id': 1, 'name': 'Alice'}

However, global variables should be used with caution in production code. For object state, it is better to express it through instance attributes or explicit state management.

4. Representing No Query Result

def find_user(user_id):
    users = {
        1: "Alice",
        2: "Bob",
    }

    return users.get(user_id)


print(find_user(1))  # Alice
print(find_user(3))  # None

dict.get() returns None when the key does not exist and no default value is provided.

But this also means: if the value actually stored in the dictionary is itself None, the return value alone cannot tell you whether the key exists.

A more rigorous check:

users = {
    1: "Alice",
    2: None,
}

if 2 in users:
    print("键存在")
else:
    print("键不存在")

Whether a key exists and whether the value for that key is None are two separate questions.

3. Differences Between None and Other Empty Values

Python has a variety of empty or falsy values that look similar, but they have different types and semantics.

1. None, False, 0, Empty Strings, and Empty Containers

Value Type Meaning Truthiness
None NoneType No value, missing state False
False bool Logical false False
0 int Integer zero False
0.0 float Floating-point zero False
"" str Empty string False
[] list Empty list False
() tuple Empty tuple False
{} dict Empty dictionary False
set() set Empty set False

They are all falsy in a boolean context, but their business semantics are not the same.

values = [
    None,
    False,
    0,
    0.0,
    "",
    [],
    {},
]

for value in values:
    print(repr(value), type(value), bool(value))

For example:

  • None: no value was provided.
  • False: an explicit logical negation.
  • 0: a valid numeric value.
  • "": a string object exists, but its content is empty.
  • []: a list object exists, but it has no elements.

You cannot treat them as equivalent objects just because they are all falsy.

2. None vs. False

a = None
b = False

print(a == b)  # False
print(a is b)  # False

The two have different types and express different meanings.

None indicates absence or no result, while False indicates an explicit logical judgment result.

For example:

is_authenticated = False
authentication_result = None

The former means the authentication result is definitively a failure; the latter means the authentication result has not yet been produced or obtained.

3. None vs. 0

count = 0

print(count is None)  # False
print(bool(count))    # False

0 is a legitimate numeric value and should not be mistaken for a missing value.

For example, in a statistics system:

  • None: the statistics have not yet been collected.
  • 0: the statistics have been completed and the result is zero.

If the business logic needs to distinguish between these two cases, use:

if count is None:
    print("数据尚未采集")
elif count == 0:
    print("统计结果为零")
else:
    print("统计结果大于零")

4. None vs. Empty String

a = None
b = ""

print(a == b)  # False
print(bool(a)) # False
print(bool(b)) # False

An empty string is still a valid string object.

When handling user input, you may need to distinguish:

  • None: No input was provided.
  • "": An empty string was provided.
  • " ": A string containing only whitespace was provided.
  • "hello": Valid text was provided.

For example:

def normalize_name(name):
    if name is None:
        return None

    name = name.strip()

    if name == "":
        return None

    return name

IV. How to Check for None

1. Use is None

This is the most recommended way to check:

value = None

if value is None:
    print("value 为空")

Reasons:

  • It directly checks whether the value is the None object.
  • It does not depend on an object's overloaded equality method.
  • The semantics are clear.
  • It conforms to Python community conventions.

2. Use is not None

value = "Python"

if value is not None:
    print("value 已经赋值")

This form is suitable for determining whether a variable has a value other than None.

3. Do not use not value to check for None

value = 0

if not value:
    print("没有值")

This code will execute, but value is actually the integer 0, not None.

If the business requirement is to check only for None:

if value is None:
    print("没有值")

If the business requirement is to check whether the value is falsy:

if not value:
    print("值为空或为假")

The semantics of the two must be distinguished.

4. Do not use type(value) == None

value = None

# Incorrect
# if type(value) == None:
#     print("没有值")

type(value) returns the type object NoneType, not a None instance.

If you really need a type check:

if isinstance(value, type(None)):
    print("value 是 None")

But in general, simply using value is None is sufficient.

V. None and Default Value Handling

Default value handling is one of the most common null-value operations in Python.

1. Use or to provide a default value

name = None

display_name = name or "匿名用户"

print(display_name)

When the left-hand object is falsy, or returns the right-hand operand.

However, this approach is not only for None:

print(0 or 100)       # 100
print("" or "默认值")  # default value
print([] or [1, 2])   # [1, 2]

If 0, False, an empty string, or an empty container is a valid value, using or may cause data to be accidentally replaced.

2. Use a conditional expression

If you only want to provide a default value for None:

name = ""

display_name = name if name is not None else "匿名用户"

print(repr(display_name))  # ''

This approach has more precise semantics.

3. Use if to check

def get_page_size(page_size):
    if page_size is None:
        page_size = 20

    return page_size

It is suitable for cases where the default value handling logic is more complex.

4. Use dictionary get()

```python config = { "host": "localhost", "port": None, } host = config.get("host", "127.0.0.1") port = config.get("port", 8080) print(host) # localhost print(port) # None ```

Points to note:

dict.get(key, default) returns default only when the key does not exist. If the key exists and its value is None, it still returns None.

If you want to treat both a missing key and None as the default value:

port = config.get("port")

if port is None:
    port = 8080

If you also need to distinguish between a key that does not exist and a key that exists with a value of None, combine this with an in check.

6. None and Mutable Default Arguments

This is a very important point in Python function design.

1. The Problem with Mutable Default Arguments

The following code has a hidden problem:

def add_item(item, items=[]):
    items.append(item)
    return items


print(add_item("A"))  # ['A']
print(add_item("B"))  # ['A', 'B']

The reason is:

  • The default argument expression is evaluated when the function is defined.
  • The default list is created only once.
  • Multiple calls share the same list object.

This can cause unexpected data contamination between calls.

2. Using None as a Default Argument

Recommended approach:

def add_item(item, items=None):
    if items is None:
        items = []

    items.append(item)
    return items


print(add_item("A"))  # ['A']
print(add_item("B"))  # ['B']

On each call, if no list is provided, a new list object is created.

3. The Limits of None as a Default Value

This pattern carries an implicit assumption: None means the caller did not provide a list.

If the business logic itself allows None to be passed explicitly, and you need to distinguish "no argument passed" from "None passed", then using None alone is not enough.

You can use a dedicated sentinel object.

_MISSING = object()


def process(value=_MISSING):
    if value is _MISSING:
        print("调用方没有传入参数")
    elif value is None:
        print("调用方显式传入 None")
    else:
        print("实际值:", value)


process()
process(None)
process(0)

A sentinel object is used to express a special state that cannot be confused with ordinary business values.

This is a more precise way to design parameters than overusing None.

7. None and Designing Function Return Values

1. Implicitly Returning None

def log_message(message):
    print(message)


result = log_message("Hello")

print(result)  # None

Functions that only perform an action and do not need to return a result typically return None implicitly.

2. Explicitly Returning None

def delete_user(user_id):
    if user_id <= 0:
        return None

    print("删除用户:", user_id)
    return None

An explicit None return can express that on certain paths the function has no business data to return.

3. Using None to Indicate a Failed Lookup

def find_user(user_id):
    users = {
        1: {"name": "Alice"},
        2: {"name": "Bob"},
    }

    return users.get(user_id)


user = find_user(3)

if user is None:
    print("用户不存在")
else:
    print(user["name"])

This is a common design for lookup interfaces.

But if the lookup result itself may legitimately be None, the return value cannot distinguish "record does not exist" from "record exists but the field is empty".

In that case, you need a more explicit return structure.

4. Using a Tuple to Express Multiple States

def find_user(user_id):
    users = {
        1: {"name": "Alice"},
        2: None,
    }

    if user_id not in users:
        return False, None

    return True, users[user_id]


found, user = find_user(2)

if found:
    print("记录存在:", user)
else:
    print("记录不存在")

This approach can distinguish whether a query result exists and whether the result itself is None.

For more complex business logic, it is recommended to use a dedicated result type or exception mechanism rather than continually adding boolean flags.

VIII. None and Type Annotations

Python type annotations can explicitly express whether a variable or function is allowed to be None.

1. Optional Types

Before Python 3.10, a common way to write this was:

from typing import Optional


def find_user(user_id: int) -> Optional[str]:
    if user_id == 1:
        return "Alice"

    return None

Optional[str] is equivalent to:

str | None

It means the return value may be a string or None.

2. Union Type Syntax in Python 3.10 and Later

def find_user(user_id: int) -> str | None:
    if user_id == 1:
        return "Alice"

    return None

str | None is a more concise modern syntax.

3. Nullable Variables

username: str | None = None

username = "Alice"
username = None

The type annotation indicates that the variable is allowed to store a string or None.

4. Type Narrowing

Static type checkers can narrow the possible type of a variable based on conditional checks.

def greet(name: str | None):
    if name is None:
        print("Hello, guest")
    else:
        print("Hello,", name.upper())

In the else branch, the type checker can infer that name is no longer None, so calling string methods is allowed.

This kind of analysis is called type narrowing.

Note that type annotations themselves do not automatically prevent invalid values from being passed in at runtime. Runtime validation still needs to be handled by program logic or dedicated validation tools.

IX. None and Exception Handling

None and exceptions are two different mechanisms for expressing errors or states.

1. None Is Suitable for Expressing an Expected No-Result

For example:

def find_product(product_id):
    return None

Not finding data may be a normal business situation, so returning None is a reasonable choice.

2. Exceptions Are Suitable for Expressing Error Conditions

def divide(a, b):
    if b == 0:
        raise ValueError("除数不能为零")

    return a / b

Division by zero is an invalid operation; using an exception expresses the problem more accurately than returning None.

3. Do Not Confuse No Result with Execution Failure

For example, reading a file:

def read_config(path):
    try:
        with open(path, encoding="utf-8") as file:
            return file.read()
    except FileNotFoundError:
        return None