None in Python

Posted: | Tags: Python

In Python, None is a built-in constant representing the absence of a value. To check if something is None, use is None or is not None.

Note that nan, which represents a "not a number", is a value of float, a floating-point number, and differs from None. For more details on nan, see the following article.

None in Python

In Python, None is an instance of NoneType.

a = None
print(a)
# None

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

It represents the absence of a value. For example, a function that does not explicitly return a value with return will return None.

def func_none():
    # do something
    pass

x = func_none()
print(x)
# None

Checking None: is None, is not None

As recommended in the Python coding standard PEP8, use is None or is not None to check if a variable is None or not None.

Comparisons to singletons like None should always be done with is or is not, never the equality operators. PEP 8 – Style Guide for Python Code | peps.python.org

a = None
print(a is None)
# True

print(a is not None)
# False

Since None is a singleton (the only instance of NoneType), object identity comparison (is, is not) should be used instead of value comparison (==, !=).

Since None is a singleton, testing for object identity (using == in C) is sufficient. The None Object — Python 3.11.3 documentation

Avoid comparing None with == or !=, or using the variable itself as a condition to indicate that it is not None. The reasons for this are explained below.

None with == or !=

Comparing None with == or != will yield the same results as is or is not.

a = None
print(a == None)
# True

print(a != None)
# False

However, == and != can be overloaded by the special methods __eq__ and __ne__, which can be freely customized.

Therefore, depending on the implementation of __eq__, == None may return True even for values that are not None. is None will always check correctly.

class MyClass:
    def __eq__(self, other):
        return True

my_obj = MyClass()
print(my_obj == None)
# True

print(my_obj is None)
# False

Truth value testing for None

In Python, all objects are evaluated as either True or False.

None is evaluated as False.

print(bool(None))
# False

However, you should not write a conditional branch that a variable x is not None as if x. Numeric values representing 0, empty strings, and empty lists are also evaluated as False, so they cannot be distinguished from None.

a = None

if a:
    print(f'{a} is not None')
else:
    print(f'{a} is None')
# None is None

a = 0

if a:
    print(f'{a} is not None')
else:
    print(f'{a} is None')
# 0 is None

In this case, you should also use x is not None.

a = None

if a is not None:
    print(f'{a} is not None')
else:
    print(f'{a} is None')
# None is None

a = 0

if a is not None:
    print(f'{a} is not None')
else:
    print(f'{a} is None')
# 0 is not None

Related Categories

Related Articles