Since when is Python None equal to None?

Question:

I always thought that Python nulls are not equal, as is common in many other languages and based on simple logic (if the value is unknown, how can it be equal to another unknown?).

However, recently I tried it, and discovered that:

Python 3.10.2
>>> None == None
True

Has it always been this way? If not, which version changed it?

Asked By: Dommondke

||

Answers:

None has always been equal to itself in python. "None == None" has always evaluated as true.

As seen from this documentation https://docs.python.org/3/c-api/none.html

Since None is a singleton, testing for object identity (using == in C) is sufficient.

Answered By: Caleb Carson

As pointed out above, this has to do with how None == None is evaluated by the __eq__.

None is a singleton object, which means that there is only one instance of it in memory at any given time. When you assign a variable to None, you are simply creating a reference to this single instance of None.

So, your example is like saying "does None point to the same object in memory as None?". The answer is yes, therefore __eq__ is fulfilled (True).

This link will explain equality in great depth if you want to read up on it.

Answered By: Thyll Müller

There is no explicit statement that None == None is true, but as far back as Python 1.5.2, there are two statements that imply this.

First, in a discussion of the equality operator:

Comparison of objects of the same type depends on the type:

  • Numbers are compared arithmetically.
  • Strings are compared lexicographically using the numeric equivalents (the result of the built-in function ord()) of their
    characters.
  • Tuples and lists are compared lexicographically using comparison of corresponding items.
  • Mappings (dictionaries) are compared through lexicographic comparison of their sorted (key, value) lists.5.2
  • Most other types compare unequal unless they are the same object; the choice whether one object is considered smaller or larger
    than another one is made arbitrarily but consistently within one
    execution of a program.

Every use of None, though, refers to the same object

2.1.7.7 The Null Object

This object is returned by functions that don’t explicitly return a
value. It supports no special operations. There is exactly one null
object, named None (a built-in name).

It is written as None.

Answered By: chepner
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.