Object Identity and Value Equality
Identity asks whether two references denote the same object. Equality asks whether the objects compare equal under their type's rule.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 2 min
In this article4 chapters
Make a pair of lists
Separate Python list literals [4] and [4] produce two lists. Their equality is true and their identity comparison is false. If the second name is bound to the first list, the two names refer to the same object. See names, objects, and bindings for how reassignment changes that relation.
Choose the test by intent
Use equality to match a user-supplied label with a known label. Use identity to detect a unique sentinel object or the singleton None. An execution trace of a mutation can expose the difference by showing which object grows and which names observe that growth.[1][2]
Follow three names pointing to two lists
Start with two separate lists containing "ready" and give the first list a second name. Comparing the two independent lists by equality succeeds at the start. Their object identities differ. The aliased names share identity and continue to observe the same current contents. Appending "sent" through one alias changes that list and makes its equality comparison against the independent ready list false. A hand trace of mutable state can record these relations row by row.
Use identity for a deliberately unique marker
A function accepting a value that can legitimately be zero, empty, or null may use a fresh private object to represent omission. An identity test on that object recognizes the marker without consulting equality rules defined by ordinary argument types. See missing values and sentinels. In a test for a newly constructed record, prefer the equality rule relating its fields when object sharing is irrelevant. Add a separate identity test only if the function promises sharing or independent copies. If changing one result should leave another untouched, verify that effect with mutable data rather than a pair of equal immutable numbers.