PythonPython Operators and ExpressionsPython identity operators
What is the difference between `is None` and `== None`?
Question 48 of 88 · Updated
On this page
- 1. The difference at a glance
- 2. Ordinary built-in values
- 3. A custom object can claim to equal None
- 4. Equality may raise an exception
- 5. Equality is not guaranteed to return a bool
- 6. What about is not None versus != None?
- 7. Practical example: optional numeric configuration
- 8. Identity functions
- 9. Performance and correctness
- 10. Common mistakes
- Frequently asked questions
- Does x is None check a memory address?
- Can __eq__ change the result of x is None?
- Is None == None true?
- Should I use is None with optional values?
- Does is None protect against exceptions while retrieving the value?
- Interview-ready answer
- Official references
Use is None to determine whether an object is actually Python's None singleton. The expression == None instead invokes Python's equality comparison protocol, which a class can customize. Although the two expressions often give the same result for ordinary built-in values, they are not semantically equivalent.
The earlier NoneType and comparison lessons introduced this distinction. This lesson demonstrates the specific failure modes of equality-based absence checks, including false matches, exceptions and non-Boolean comparison results.
1. The difference at a glance#
| Property | x is None | x == None |
|---|---|---|
| Meaning | Is x the actual None object? | Does the equality protocol consider x equal to None? |
| Custom equality methods | Not invoked | May be invoked |
| Result when successful | Always a bool | May be a non-Boolean object |
| Can a distinct object report a match? | No | Yes |
| Recommended for absence checks | Yes | No |
None is the sole instance of NoneType. Assigning None to another name does not create a different None object. Identity comparison tests whether two operands designate the same object; it cannot be overloaded by defining an equality method.
The equality operator, on the other hand, asks for a value comparison. It follows the rich comparison dispatch rules of Python's data model. These can involve the operands' __eq__ methods and a fallback to identity when the applicable methods decline the comparison using NotImplemented.
For a bound name x, the identity operation itself does not invoke custom equality or truth-testing hooks. Evaluating a more complicated operand, such as a property or function call, can still have side effects or raise exceptions before the identity test occurs.
2. Ordinary built-in values#
PYTHONfor value in (None, 0, False, '', []): print(repr(value), value is None, value == None)
Output:
None True True
0 False False
False False False
'' False False
[] False FalseThe two checks agree for these particular objects. That agreement is not evidence that they are interchangeable for every possible Python object.
The example deliberately uses equality with None for comparison. In normal application code, follow PEP 8 and use is None or is not None.
Notice that zero, False and empty collections are distinct from None, even though all are falsy. A condition such as if not value would include those other values. Choose the condition that expresses the actual domain requirement: absence, falsehood, emptiness or something else.
3. A custom object can claim to equal None#
PYTHONclass EqualToNone: def __eq__(self, other): return other is None x = EqualToNone() print(x == None, x is None, None == x)
Output:
True False TrueThe object x is an instance of EqualToNone, not NoneType. Its custom __eq__ method nevertheless reports equality with None.
The expression None == x can also invoke x's equality behavior through the comparison protocol. Merely reversing the operands therefore does not turn equality into an identity check.
This example intentionally implements an unusual equality contract to demonstrate the mechanism. A production class should normally implement coherent equality semantics appropriate to its domain and should use NotImplemented for unsupported operand pairings.
Identity provides a language-level test of the actual singleton. Equality follows the types' comparison behavior. The result of equality is not reliable proof that a variable contains None.
4. Equality may raise an exception#
PYTHONclass NoComparison: def __eq__(self, other): raise RuntimeError('comparison forbidden') x = NoComparison() print(x is None, x is not None) try: x == None except RuntimeError as exc: print(str(exc))
Output:
False True
comparison forbiddenAn equality comparison can execute arbitrary code defined by a class. That code can raise an exception, perform an expensive calculation or have other side effects.
The identity checks do not call __eq__, so they correctly establish that x is not None without triggering the example's exception.
Do not catch every exception from equality and reinterpret it as absence. An error in a comparison is not proof that an object is missing. If the actual question is whether the object is None, use identity directly.
5. Equality is not guaranteed to return a bool#
A rich comparison method may return a non-Boolean object. When that result is used in a condition, Python subsequently tests its truth value.
PYTHONclass Verdict: def __bool__(self): raise ValueError('ambiguous result') class Record: def __eq__(self, other): return Verdict() x = Record() print(type(x == None).__name__, x is None) try: if x == None: pass except ValueError as exc: print(str(exc))
Output:
Verdict False
ambiguous resultThe equality expression itself produces a Verdict instance. The if statement attempts to evaluate that instance's truth value, causing the exception.
This minimal standard-library-free example reproduces the general kind of issue that can arise with objects whose comparisons produce collections of results instead of a single Boolean. Some numerical array libraries use elementwise equality and reject ambiguous truth tests. The exact behavior of a particular third-party library depends on its type, shape and version; no third-party package behavior is assumed or tested here.
x is None always produces a Boolean identity result after the operands have been successfully evaluated. It does not request an elementwise comparison or truth-test the value of x.
6. What about is not None versus != None?#
The negative identity form is is not None. Inequality with != uses the rich inequality comparison protocol and can be customized independently of equality.
PYTHONclass Strange: def __eq__(self, other): return True def __ne__(self, other): return True x = Strange() print(x == None, x != None, x is None, x is not None)
Output:
True True False TrueThe class deliberately defines inconsistent comparison results. Python does not guarantee that independently implemented __eq__ and __ne__ methods form a logically consistent pair. By contrast, is not is the logical inverse of is for the same evaluated operands.
For ordinary code, write if result is not None: when the intended branch is "a result exists." Avoid if result != None:, and do not write if result: unless all falsy values are intended to count as absent.
7. Practical example: optional numeric configuration#
PYTHONdef limit(value: int | None = None) -> int: if value is None: return 10 return value print(limit(), limit(0), limit(5))
Output:
10 0 5The function uses None to represent an omitted or unspecified limit. An explicit zero is preserved, which would not happen with value or 10.
The annotation int | None describes the allowed type union (Python 3.10 and later). It does not enforce the type at runtime. A static type checker can generally narrow an optional value after an explicit None check, subject to its analysis rules. No static type checker was executed for this lesson.
For a public configuration interface, validate the actual input type and any permitted numeric range separately. Absence and validity are different questions.
If omission and explicit None have different meanings, use a separate sentinel or a mapping-key presence test, as demonstrated in the preceding NoneType lesson.
8. Identity functions#
The standard-library operator module exposes callable forms of the identity operators.
PYTHONimport operator x = None print(operator.is_(x, None), operator.is_not(0, None))
Output:
True TrueThese functions can be useful in APIs that require callable predicates. Ordinary inline code is usually clearer with is None and is not None directly.
9. Performance and correctness#
An identity comparison requires only an identity decision after both operand expressions have been evaluated. For ordinary object references, this is a constant-size operation in common Python implementations. An equality comparison may perform type-dependent dispatch and arbitrarily complex work.
Do not choose the identity check solely because it is potentially faster. The decisive reason is correctness: it expresses exactly the singleton relationship required by an absence check.
For example, if a variable refers to a long list, is None does not need to compare the list's elements. A custom equality comparison could do substantial work. Python makes no universal complexity guarantee for a user-defined __eq__ method.
10. Common mistakes#
| Mistake | Correct approach |
|---|---|
| Using == None because it works with basic values | Use is None for the singleton test |
| Writing None == x to avoid custom equality | Use x is None; reversing equality does not eliminate its protocol |
| Replacing is None with not x | Use a truth test only when every falsy value has the intended meaning |
| Catching comparison exceptions and treating them as missing values | Test identity explicitly and handle genuine comparison failures separately |
| Comparing an arbitrary value with is instead of == | Reserve identity for same-object relationships; use equality for value comparisons |
| Treating None checks as full validation | Validate expected types, ranges and other domain constraints separately |
Frequently asked questions#
Does x is None check a memory address?#
It checks object identity. CPython may implement identity using object references, but the language guarantee is same-object identity, not a particular numeric address.
Can __eq__ change the result of x is None?#
No. Identity comparison is not dispatched through __eq__.
Is None == None true?#
Yes. For the None singleton, both None == None and None is None are True. Their general semantics remain different.
Should I use is None with optional values?#
Yes, when None specifically represents absence. It distinguishes None from other falsy or custom values.
Does is None protect against exceptions while retrieving the value?#
No. A property, index expression or function call can raise while evaluating the left operand. Identity avoids invoking equality methods after the operands are obtained; it does not suppress exceptions from operand evaluation.
Interview-ready answer#
is None checks whether a value is the actual None singleton, whereas == None invokes the equality comparison protocol. A custom object may compare equal to None, raise during equality or return a non-Boolean comparison result. Identity cannot be customized through __eq__ and always returns a Boolean when its operands have been successfully evaluated. Use is None and is not None for explicit absence checks, and reserve == for value equality. Do not confuse absence with general falsiness, because zero, False and empty collections are valid distinct values.
Official references#
- PEP 8 — Programming Recommendations
- Python Language Reference — Identity comparisons
- Python Language Reference — Value comparisons
- Python Language Reference — Basic customization and rich comparison
- Python Language Reference — None
- Python Standard Library — operator
- Python Standard Library — typing.Optional
Verification note: All seven included runnable example groups were executed independently on CPython 3.13.5 and matched their documented outputs, including the two caught comparison-related exceptions. The fenced Mermaid flowchart was manually reviewed. The local Mermaid package and CLI were unavailable; parser-level and public-site rendering were not tested. No third-party numerical library or static type checker was tested. Official references are supplied under the authorized offline research exception; live documentation and the Supabase changelog could not be checked.
References
- 1.PEP 8 — Programming Recommendationspeps.python.org
- 2.Python Language Reference — Identity comparisonsdocs.python.org
- 3.
- 4.Python Standard Library — operatordocs.python.org
- 5.Python Standard Library — typing.Optionaldocs.python.org
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design