Equality (==
) and Identity (is
)
Equality (
==
): Checks if two objects represent the same data.Identity (
is
): Checks if two objects are the same object in memory.
Default Behavior in Custom Classes
By default, equality checks in custom classes behave like identity checks.
This can be customized using the
__eq__
method.
Integer Identity Quirks
Python optimizes integer objects for values between -5 and 256.
This optimization can sometimes extend to other integers within the same scope.
Quirkiness Explained
Assigning the same integer value to different variables doesn’t guarantee identity.
This behavior is quirky because it defies the intuition that two variables with the same value should be identical. However, Python’s memory optimization rules make this untrue for integers outside the -5 to 256 range.
String Optimization
Python also optimizes short strings.
When to Use is
Rarely used except for checking sentinel values like
None
.
Summary
- Use
==
for equality checks. - Use
is
mainly forNone
checks, as recommended by PEP 8.